Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery compare two String from different elements

I want to compare a select option with text content. can it be achieved. though the strings are same, they don't match while comparing.

<div id="dateRange">
          <p>27 Nov 2016_26 Dec 2016</p>
</div>

and Select option be like:

<select id="dateRangeSelect" onchange="showHideForms(this);"><option value="27 Nov 2016_26 Dec 2016" selected>nov-dec</option></select>

in Jquery I am comparing:

$("#dateRangeSelect").val() and $("#dateRange").text()

though they look same in console output, they dont match in if condition can some one comment on what might be wrong.

like image 571
Venkatesh Bhagavath Avatar asked Feb 22 '26 19:02

Venkatesh Bhagavath


2 Answers

Try to compare not the $("#dateRange").text(), because it returns also the p tag as a text. So change it into $("#dateRange p").text()

console.log($("#dateRangeSelect").val());
console.log($("#dateRange p").text());

console.log($("#dateRangeSelect").val() === $("#dateRange p").text());

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dateRange">
          <p>27 Nov 2016_26 Dec 2016</p>
</div>


<select id="dateRangeSelect" onchange="showHideForms(this);"><option value="27 Nov 2016_26 Dec 2016" selected>nov-dec</option></select>
like image 199
Suren Srapyan Avatar answered Feb 25 '26 08:02

Suren Srapyan


Need to compare the text inside p tag with the value. Also use .trim() to remove any white space

($("#dateRangeSelect").val()=== $("#dateRange p").text().trim())
like image 30
brk Avatar answered Feb 25 '26 07:02

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!