简体   繁体   English

根据h1文本设置选择值

[英]Set select value based on h1 text

I have the following form: 我有以下表格:

$(function() {
    if () {}
    else {}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Sandeep</h1>
<form>
    <select>
        <option>Non Selected</option>
        <option selected>Michael</option>
        <option>Sandeep</option>
    </select>   
</form>

I want to find a way to say in javascript: if the text of the h1 is Sandeep the option selected will be sandeep . 我想在javascript中找到一种说法:如果h1的文本是Sandeep则选择的选项将是sandeep

I don't know how to define the condition inside the if statement. 我不知道如何在if语句中定义条件。 Any ideas? 有任何想法吗?

Use .text() to get the text in the <h1> , and compare that with Sandeep . 使用.text()获取<h1>的文本,并将其与Sandeep进行比较。 Use .val() to set the value of the <select> 使用.val()设置<select>的值

 if ($("h1").text() == "Sandeep") { $("select").val("Sandeep"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Sandeep</h1> <form> <select> <option>Non Selected</option> <option selected>Michael</option> <option>Sandeep</option> </select> </form> 

Simple solution is to directly set the value of select tag to that of the text inside h1 . 一种简单的解决方案是将select标记的值直接设置为h1

JS CODE: JS代码:

$(function () {
   var selectedText = $('h1').text();
   $('select').val(selectedText);
});

Live demo @ JSFiddle: http://jsfiddle.net/dreamweiver/k151ye9h/ 现场演示@ JSFiddle: http : //jsfiddle.net/dreamweiver/k151ye9h/

See inline comments 查看内联评论

 $(function() { var text=$('.name').text(); //get the header value by referring its class $('select').find("option[text=" + text + "]").attr("selected", true); //^^Find that particular option whose text is same as in header }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 class="name">Sandeep</h1> <form> <select> <option>Non Selected</option> <option text="Micheal" selected>Michael</option> <option text="Sandeep">Sandeep</option> <!--Add text property to each option--> </select> </form> 

Simply use Jquery selector to select the value based on "h1". 只需使用Jquery选择器即可基于“ h1”选择值。

 $(document).ready(function() { if ($("h1").text() == "Sandeep") { $("select").val("Sandeep"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Sandeep</h1> <form> <select> <option>Non Selected</option> <option selected>Michael</option> <option>Sandeep</option> </select> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM