Mina Magdy
Mina Magdy

Reputation: 141

JS add attribute to string

I have a post ajax that return retorno1 and just to get it simple i put their output as string value as ajax posted like the example .. then I need to add more than 1 option that the value is 0 so I need to say if the value is 0 show the selected item "NON" and if the value other so show it and select it.

I'm using setAttribute("selected", "selected") but I know it's wrong, so what is the correct code to add attribute to this string?

var i = 0;
var returno1 = "<option value='21'>Hello</option><option value='22'>Bye</option>";
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(pre)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();

$.each($.parseHTML(pre),function(i,item){
    var val_drop  =($(item).val());
    var text_drop =($(item).html());

    if (val_drop == dep_dr){
        jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
    }else if(dep_dr == "0"){
        jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
    }
})

Upvotes: 1

Views: 1897

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Working fiddle

Try to use attr() or prop() to set or get attribute to elements, check example bellow :

jQuery("#departamento_drop").empty();

$.each($.parseHTML(pre),function(i,item){
    var current_itme=$(item);
    var val_drop  =current_itme.val();
    var text_drop =current_itme.html();

    if (val_drop == dep_dr || dep_dr == "0"){
        current_itme=current_itme.attr("selected", "selected");
    }

    jQuery("#departamento_drop").append(current_itme);
})

Hope this helps.

Upvotes: 1

user5909071
user5909071

Reputation: 1

Why do you need use strings? Use objects insted.

var values = [{val:33, title:'Hi'},{val:34, title:'Bue'},{val:0, title:'-------NA-------'}],
    selected = 34;
values.forEach(function(item){
    $('#dd').append($('<option>', {value:item.val, text:item.title, selected: item.val==selected}));
})

Upvotes: 0

Related Questions