So I have lots of radio buttons with same name but different ID and I wan't specific one of them to be selected on page load. The ID of desired button is saved to the database. I've tried this kind of solution for the actual ajax call, but alas it didn't work.
$.ajax({
type: "POST",
url: "load_config.php",
dataType: "json",
data: dataString,
success: function(data)
{
var buttonID = "#"+data.buttonID; // data.buttonID = "button5"
$(buttonID).attr("checked", true);
}
});
while the HTML part is in this sorta manner, except with a whole lot more of buttons:
<input type="radio" id="button1" name="example" va开发者_如何学Pythonlue="value1"/>
<input type="radio" id="button2" name="example" value="value2"/>
<input type="radio" id="button3" name="example" value="value3"/>
<input type="radio" id="button4" name="example" value="value4"/>
<input type="radio" id="button5" name="example" value="value5"/>
Double check your JSON coming back, your overall approach is correct, you can test it here: http://jsfiddle.net/nick_craver/KuK3Z/
I would bet that your data.buttonID
isn't quite what you think it is, or your code isn't running inside a document.ready
, like this:
$(function() {
$.ajax({
type: "POST",
url: "load_config.php",
dataType: "json",
data: dataString,
success: function(data)
{
var buttonID = "#"+data.buttonID; // data.buttonID = "button5"
$(buttonID).attr("checked", true);
}
});
});
If it's not running in a document.ready
and your AJAX call finishes before your elements are ready, the $("#button5")
selector won't find anything to check. Alternatively, and much better if you can could be to just render a checked="checked"
inside the correct <input />
when you render the page, and eliminate the AJAX call altogether.
Try to check your data response:
$(function() {
$.ajax({
type: "POST",
url: "load_config.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert(data['buttonID']);
}
});
});
if is undefined check your php or my last solution, otherwise try:
$(function() {
$.ajax({
type: "POST",
url: "load_config.php",
dataType: "json",
data: dataString,
success: function(data)
{
$("#"+data['buttonID']).attr("checked",true);
}
});
});
I've a problem once time returning the Json to jquery, the json string was returned with many slashes... try this in case the first solution gaves to you an error (this will report the string returned form server without decoding the json):
$(function() {
$.ajax({
type: "POST",
url: "load_config.php",
dataType: "text",
data: dataString,
success: function(data)
{
alert(data);
}
});
});
Sorry for my english. tell me something if it worked...
精彩评论