How can I change the input value through a pop up.
Let's say I'm building a shopping platform and when the user clicks on the quantity a popup appears. The quantity will be diferent for other products. Here is my code
HTML:
<form action="">
<input class="qnt" type="text" placeholder="Escolha a quantidade">
<input class="qnt" type="text" placeholder="Escolha a quantidade">
<input class="qnt" type="text" placeholder="Escolha a quantidade">
<input class="qnt" type="text" placeholder="Escolha a quantidade">
</form>
<div class="pop_up">
<div class="pop_up_container">
<input class="pop_up_campo" type="text">
<button class="pop_up_confirm">Confirmar!</button>
</div>
</div>
jQuery:
var qnt = $('.qnt');
$(document).ready(function() {
$('.pop_up').hide();
})
qnt.click(function() {
$('.pop_up').show('fast');
$('.pop_up_campo').click(function() {
$('.pop_up_confirm').click(function() {
$(this).val(qnt.val($('.pop_up_campo').val()));
$('.pop_up').hide();
})
})
});
答案 0 :(得分:0)
你可以检测到&amp;使用点击事件中的e.target
保存单击的输入,然后写入已保存的输入
var input;
qnt.click(function(e) {
//Save the selected input
input = e.target;
$('.pop_up').show('fast');
});
$('.pop_up_campo').click(function() {
$('.pop_up_confirm').click(function() {
//Write into selected input
$(input).val($('.pop_up_campo').val());
$('.pop_up').hide();
})
})
答案 1 :(得分:0)
您可以使用函数外部的变量来跟踪您选择的输入(因此想要更改)。你不想把按钮点击进入输入点击 - 弹出窗口内的输入点击似乎不应该实际触发任何事件。所以分开弹出弹出窗口的click函数,以及在关闭弹出窗口时更改输入值的click事件
var selectedInput = '';
$(document).on('click', '.qnt', function() {
selectedInput = $(this);
$('.pop_up').show('fast');
});
$(document).on('click, '.pop_up_confirm', function() {
selectedInput.val($('.pop_up_campo').val());
$('.pop_up').hide();
selectedInput = '';
});
答案 2 :(得分:0)
这就是你要找的东西。 Play with it in Codepen
$(document).ready(function() {
//all your jquery code should be wrapped up in document ready
var id = 1000;
//for each .qnt, apply a click listener
$('.qnt').each(function(){
var $thisQuantity = $(this);
$thisQuantity.attr('data-id', id++);
$thisQuantity.click(function() {
//copy the .qnt value to pop up input
$('.pop_up_campo').val($thisQuantity.val());
$('.pop_up_campo').attr('data-id', $thisQuantity.attr('data-id'));
$('.pop_up').show('fast');
$('.pop_up_campo').focus();
});
});
//apply a click handler to your pop_up button
$('.pop_up_confirm').click(function() {
var relatedQntId = $('.pop_up_campo').attr('data-id');
var newValue = $('.pop_up_campo').val();
$(".qnt[data-id='"+relatedQntId+"']").val(newValue);
$('.pop_up').hide();
});
});
答案 3 :(得分:0)
您可以使用$(this).data("count", 10)
在点击的元素中存储数据。
有关如何使用该功能的更多信息,请参阅https://api.jquery.com/data/。