D
D
Dima Samsonov2018-02-27 15:22:13
JavaScript
Dima Samsonov, 2018-02-27 15:22:13

How to pass .val() on click to input?

Good evening.
ran into a small problem.
I have several blocks.

<div class="block-info">
            <span class="block-food">Сосиска в тесте</span>
            <button class="block-btn">Заказать</button> 
       </div>

       <div class="block-info">
            <span class="block-food">Сосиска без теста</span>
            <button class="block-btn">Заказать</button> 
       </div>
//один инпут

       <input class="out" type="text">


all blocks and the content inside them have the same class.

I need to make it so that when you click on , the value c of the span tag with class="block-food" of THIS BLOCK is pulled up!! Sausage with text (order). I puzzled for a long time, wrote this structure, but it does not work (.
<button class="block-btn">Заказать</button>
<input class="out" type="text">

$('.block-info').on('click', '.block-btn' function(){
    var info = $(this).find('.block-food').val();
    $('.out').val(info).html('заказать')
})


I know that it is not written very correctly,
I am a beginner, so I will be grateful for your help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nick Sdk, 2018-02-27
@dima_toster

$('.block-btn').on('click', function(){
  var food = $(this).parent().find('.block-food').text();
  // или так
  // var food = $(this).prev().text();
  $('.out').val(food);
  // или со словом "заказать"
  // $('.out').val(food + ' (заказать)');
});

https://jsfiddle.net/ep4tareh/

T
TheRevan, 2018-02-27
@TheRevan

$('.block-btn').click(function(){
  var info = $(this).closest('.block-info').find('.block-food').text();
  $('.out').val(info);
})

P
Pavel Novikov, 2018-02-27
@paulfcdd

You need to use the .parent() property:

$(document).ready(function() {
$('.block-btn').on('click', function() {
var text = $(this).parent().find('.block-food').text();
$('.out').val(text);
});
});

https://jsfiddle.net/o2gxgz9r/28173/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question