我有以下DIV:
<div id="modalUpdate">
<div class="modal-content">
<div class="header">
<h2>Update Item in Your Shopping Cart</h2>
</div>
<div class="copy">
<label>Item:</label>
<select id="itemChoice">
<option value="Wine" selected>Wine</option>
<option value="Shot">Shot</option>
<option value="Beer">Beer</option>
</select>
<br /><span id="spanPrice"></span><br /><br />
<label>Quantity:</label>
<input type="text" id="quantity" name="quantity" placeholder="10">
<label>Price:</label>
<input type="text" id="price" name="price" placeholder="$10.00">
</div>
<div class="cf footer">
<input type="button" value="Cancel" id="cancelUpdate"><input type="button" value="Update Item" id="updateTable">
</div>
</div>
<div class="overlay"></div>
</div>
我想使用JQuery访问SELECT和每个文本框,以便我可以将值填充到其中。我尝试了以下方法:
var values = $('#'+p.id+' td').map(function(i,c){ return $(c).text(); }).get();
alert(p.id);
alert(values);
$("#modalUpdate #modal-content .copy #itemChoice").val(values[0]);
$("#modalUpdate #modal-content .copy #spanPrice").text("Each: " + values[1]);
$("#modalUpdate #modal-content .copy #quantity").val(values[2]);
$("#modalUpdate #modal-content .copy #price").val(values[3]);
警报显示正确的值,但由于某种原因字段未填充。
如何修复代码以使其有效?
答案 0 :(得分:2)
modal-content
是一个类,因此jquery中的选择器应如下所示:
$("#modalUpdate .modal-content .copy #itemChoice").val(values[0]);
话虽如此,因为ID选择器只能 选择单个元素(根据定义,ID必须在页面上唯一),您可以直接使用子ID:
$("#itemChoice").val(values[0]);
$("#spanPrice").text("Each: " + values[1]);
$("#quantity").val(values[2]);
$("#price").val(values[3]);
答案 1 :(得分:1)
如果我发现你的问题,这应该可行
$(function() {
// Select all <select> tag inside div#modalUpdate and callback this function for eac of them
$('div#modalUpdate select').each(function() {
// alert the ID attribute for the current SELECT tag as well as it's VALUE
alert('SELECT#' + $(this).attr('id') + ' = ' + $(this).val())
});
// Select all INPUT element inside div#modalUpdate having [type="texte"] and execute a callback function for each of them
$('div#modalUpdate input[type="text"]').each(function() {
if ('quantity' === $(this).attr('id')) {
// Check ID for the current matched element before running a specific action
$(this)// .actionIfTrue();
}
else if ('price' === $(this).attr('id')) {
// Same as first condition
$(this)// .actionIfTrue();
}
});
});