如果我使用一个文本框和3个div,如何在该div中设置输入的值? 这是我的代码。我必须从选中的单选按钮中获取div值。同样,我如何获得文本框值?
这是我的代码。
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" value="456"/>
</div>
<div name="deff" id="val1" x>123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val2" >456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" value="678" />
</div>
<div name="deff" id="val3" >678</div>
<span>jquery</span>
<br></br>
<div name="deff" id="val4" >
<input type="radio" name="user_options" value="675" />
</div>
<input class="text-input" id="other-input" size="5" value="">
<span>JS</span>
<br></br>
<div><button id="radio_submit" type="button">Show Selected Radio</button></div>
</form>
<div id="valueee"></div>
<script>
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var check = $("input[name=user_options]:checked").parent().next().text();
if(!check){
alert('Please select options!');
}else{
$('#valueee').html(check);
}
});
});
</script>
答案 0 :(得分:1)
不确定您的意思,但可能需要再次检查并尝试 val()
,如果 undefined
,
$(document).ready(function () {
$("#radio_submit").click(function (e) {
var check = $("input[name=user_options]:checked").parent().next().text();
if (!check) var check = $("input[name=user_options]:checked").parent().next().val();
if (!check) {
alert('Please select options!');
} else {
$('#valueee').html(check);
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val1" x>123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val2">456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" value="678" />
</div>
<div name="deff" id="val3">678</div>
<span>jquery</span>
<br></br>
<div name="deff" id="val4">
<input type="radio" name="user_options" value="675" />
</div>
<input class="text-input" id="other-input" size="5" value="" />
<span>JS</span>
<br></br>
<div>
<button id="radio_submit" type="button">Show Selected Radio</button>
</div>
</form>
<div id="valueee"></div>
&#13;
答案 1 :(得分:1)
您可以使用is()
检查下一个元素是div
还是input
。如果input
然后使用.val()
读取值,则使用.text()
。
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var next = $("input[name=user_options]:checked").parent().next();
//check if next element is input and read value otherwise read text
var check = '';
if($(next).is('input'))
check = $(next).val();
else
check = $(next).text();
if(!check){
alert('Please select options!');
}else{
$('#valueee').html(check);
}
});
});
<强> DEMO 强>