Reputation: 2315
I'm going to make a auto complete form. In which the options of the form like address, telephone, fax and department are auto select after a username is selected by a drop down (auto suggest) list.
The whole process is completed. But only one thing - the radio button. I don't have any idea how to make it selected from a value return by ajax. Here is my code.
HTML
<form id="inst_name">
Address : <textarea name="addr" id="addr"></textarea>
Telephone : <input type="text" name="tel" id="tel" />
Department :
<input type="radio" name="dep" id="dep1" value="1" /><label>Dep 1</label>
<input type="radio" name="dep" id="dep2" value="2" /><label>Dep 2</label>
<input type="radio" name="dep" id="dep3" value="3" /><label>Dep 3</label>
</form>
Javascript
$('#inst_name').blur(function(){
$.ajax({
url: 'inc/autoform.json.php',
dataType:'json',
data: {name:$('#inst_name').val()},
success: function(data){
$('#inst_addr').val(data.addr);
$('#inst_tel').val(data.tel);
$('#hidden_dep').val(data.dep);
}
});
});
For example, if an ajax returned data.dep="1" so the Dep 1 should be selected.
Upvotes: 0
Views: 465
Reputation: 2783
$("#inst_name input[value="+data.dep+"]").prop("checked", true);
EDIT to add the explanation:
The radio inputs all share the same name but they are different html elements, therefore you need to select the input whose value matches the one you received and check it.
To select the radio button whose value is the one you're looking for you use this code:
$("#inst_name input[value="+data.dep+"]")
and then you just check it with this code:
.prop("checked", true);
Upvotes: 1
Reputation: 2106
by selecting nth radio
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="inst_name">
<input type="radio" name="dep" value="1" /><label>Dep 1</label>
<input type="radio" name="dep" value="2" /><label>Dep 2</label>
<input type="radio" name="dep" value="3" /><label>Dep 3</label>
</div>
<script>
var n = 0;
$($('#inst_name input:radio')[n]).prop('checked', true);
</script>
</body>
</html>
Upvotes: -2
Reputation: 13243
You can simply loop through them then check the one that matches the value.
$("[name=dep]").each(function(i,v){
var dep2 = $(this).val();
if(data.dep == dep2) $(this).prop("checked",true);
});
Upvotes: 1
Reputation: 22405
By calling val()
in the success callback, you are simply assigning a value to the element.
You would want to manipulate the checked
attribute of the element in the callback.
$('#inst_addr, #inst_tel, #hidden_dep').prop("checked",true);
Upvotes: 1