Home  >  Article  >  Web Front-end  >  A brief analysis of Jquery operation selection

A brief analysis of Jquery operation selection

高洛峰
高洛峰Original
2016-12-28 09:57:02924browse

Without further ado, please look at the code:

<select id="Select1">
  <option value="one">一</option>
  <option value="two">二</option>
  <option value="thr">三</option>
  <option value="tho">四</option>
</select>

Comments:

(1) Assign a value to the drop-down box: $("#Select1").val("二"); At this time, the option with value two has been selected. You can get the index at this time to be 1 through $("#Select1")[0].selectedIndex or $("#Select1").get(0).selectedIndex. The drop-down box The index starts from 0

(2) By setting the attribute $("#Select1 option[value='two']").attr('selected',true); you can also set the selection. In fact, Equivalent to assignment

(3) Get the text corresponding to the selected value:

      1. Get by value: $("#Select1 option[value='" + value + "']") .text() or $("#Select1").find("option[value='" + value + "']").text()

2. Obtain through the selected state: $(" #Select1").find("option:selected").text()

(4) Cascade of drop-down boxes:

Many times the cascade of select is used, that is, the second The value of each select changes with the value selected by the first select. This is very simple in jQuery.

For example: $(".selector1").change(function(){

// Clear the second one first

$(".selector2").empty ();

// In actual applications, multiple options here are generally generated using a loop

var option = $("<option>").val(1).text("pxx");
  $(".selector2").append(option);
  });

(5) Select the corresponding option through the value of the text in the option Value

var count = $("#Select1 option").length;
   for (var i = 0; i < count; i++) {
    if ($("#Select1").get(0).options[i].text == $(this).val()) {
     $("#Select1").get(0).options[i].selected = true;
     break;
    }
   }

Ps: How to remove leading and trailing spaces in jquer: $.trim(value);

The above is the entire content of this article. I hope the content of this article can help everyone's study or work. Please help me, and I hope you can support the PHP Chinese website!

Please pay attention to the PHP Chinese website for more articles on Jquery operation selection!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn