1

I have a string:

var html = '<select">\
<option></option>\
<option>Mr</option>\
<option>Mrs</option>\
<option>Ms</option>\
<option>Master</option>\
<option>Miss</option>\
<option>Dr</option>\
<option>TBA</option>\
</select>';

I'm wanting to place a selected within the 'Master' option. How could I do this?

I've tried:

var html = $($(html).find("option").filter(function () { return $(this).html() == "Master"; }).prop('selected', true));

I don't know how to search a string like I would the DOM.

JSBIN

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
ditto
  • 5,917
  • 10
  • 51
  • 88

4 Answers4

4

Why not just do a string replace like this:

html = html.replace('<option>Master</option>','<option selected>Master</option>');

SunKnight0
  • 3,331
  • 1
  • 10
  • 8
3

Use :contains() selector and set attribute using attr()

$(this).html() == "Master";
}).prop('selected', true));
var html = '<select>\
<option></option>\
<option>Mr</option>\
<option>Mrs</option>\
<option>Ms</option>\
<option>Master</option>\
<option>Miss</option>\
<option>Dr</option>\
<option>TBA</option>\
</select>';

console.log(
  $(html)
  .find('option:contains("Master")') // getoption which contains master
  .attr('selected', true) // set selected attribute
  .end()[0].outerHTML // back to previous selector and get dom  object and it's outerHTML property
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

With filter() method

var html = '<select>\
<option></option>\
<option>Mr</option>\
<option>Mrs</option>\
<option>Ms</option>\
<option>Master</option>\
<option>Miss</option>\
<option>Dr</option>\
<option>TBA</option>\
</select>';

console.log(
  $(html)
  .find("option") // get all options
  .filter(function() { // filter option which contains master
    return $(this).text() == "Master";
  }).attr('selected', true) // set selected attribute
  .end() // back to option selector
  .end()[0].outerHTML // back to html selector and get dom  object and it's outerHTML property
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Change your code to:

/*jshint multistr: true */
var html = 
 '<select class="form-control honorific">\
   <option>Mr</option>\
   <option>Mrs</option>\
   <option>Ms</option>\
   <option>Master</option>\
   <option>Miss</option>\
   <option>Dr</option>\
   <option>TBA</option>\
 </select>';

$(function() {
    var temp = "Master"; 
    $('body').append(html);
    $(".form-control").val(temp);
});
Huy Chau
  • 2,178
  • 19
  • 26
-2

This may help :

var elements = $(theHtmlString);
var found = $('.FindMe', elements);

Source:How to get an HTML element from a string with jQuery

Community
  • 1
  • 1
  • Because this answer the specific question. It only shows how to select a specific element but not how to add an attribute or anything. – putvande May 27 '16 at 14:34