ditto
ditto

Reputation: 6277

Selecting elements within a string

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

Upvotes: 1

Views: 867

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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>

Upvotes: 3

Huy Chau
Huy Chau

Reputation: 2240

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);
});

Upvotes: 1

Sangamesh Davey
Sangamesh Davey

Reputation: 75

This may help :

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

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

Upvotes: -2

SunKnight0
SunKnight0

Reputation: 3351

Why not just do a string replace like this:

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

Upvotes: 4

Related Questions