user1601973
user1601973

Reputation: 572

Set option of the Select box according to JSON result

I actually have some questions but I will start with the main one. I want to set the value of Select box on the basis of JSON.

Here's the HTML in question,

<label class="lbl">Office: </label>
    <select tab-index="6" class="required" name="office" class="off">
        <option value="">---------</option>
        <option value="U">London</option>
        <option selected="selected" value="R">Delhi</option>
        <option value="W">Lisbon</option>
    </select>

JSON sends it like this, I can't show the full JSON since it's too big, but I will show a part, Location: "U".

Here's the JS part:

if (data.Office === "R") {
    $('select option[value="Delhi"]').prop('selected', true);
}
if (data.Office === "U") {
    console.log('here');
    $('.off option[value="London"]').attr('selected', 'selected');
}
if (data.Office === "W") {
    $('select option[value="Lisbon"]').prop('selected', true);
}

But it's not working? Can any one point out why?

Moreover, I have a list of managers say and I am also getting that in JSON. So I am doing this,

for (var i = 0; i < data.Managers.length; i++) {
    find_input = $('input[name="project_manager[]"').length;
    if (find_input != data.Managers.length) {
        $('<input type="text" name="project_manager[]" class="" value="" />').appendTo('#managers');
    }
    console.log(data.Managers[i].Manager);
    $('input[name="project_manager[]"').each(function() {
        $(this).val(data.Managers[i].Manager);
    });
}

No of textboxes depend on the number of managers, but it only sets the value of last item from the array of managers in text boxes that are appended. Why?

Moreover I am not able to set value of textarea in Firefox like this:

$('textarea#some_id').val(data.Description);

It works in Chrome though.

Upvotes: 0

Views: 710

Answers (2)

First you need to add the character "<" in the beginning of the 3rd option of the select box:

<option selected="selected" value="R">Delhi</option>

Now, in the JS code, your problem is that you're using the wrong value. Instead of:

$('select option[value="Lisbon"]').prop('selected', true);

You must use:

$('select option[value="W"]').prop('selected', true);

I hope it help.

Upvotes: 1

Tim Croydon
Tim Croydon

Reputation: 1896

I think your selectors should be of the form:

$('select option[value="R"]').prop('selected', true);

Note the value is the same as the value in the HTML, not the displayed string (i.e. 'R' instead of 'Delhi').

Also, you should be using prop() consistently for selected flag, as described here by John Resig.

Upvotes: 0

Related Questions