Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery working only when click first time not on other time

Hi I am having given code

<div class='school-name'>
    <select name="merry" id="exams">
              <option value="test1">test1</option>
              <option value="test2">test2</option>
              <option value="test3">test3</option>
    </select>

    <select name="date[year]" id="date_year">
        <option value="2013">2013</option>
        <option value="2014">2014</option>
        <option selected="selected" value="2015">2015</option>
    </select>
    <button type="button" class='farji'>Click Me!</button>
</div>
<div id='myText'> hii farjiz calendar January</div>

and in my js i have included this

$(document).ready(function() {
  $('.farji').click(function(){    
    currentSelectedYear = $("#date_year option:selected").val()
    alert(currentSelectedYear)
    switch ($("#exams option:selected").val()) {
      case 'test1':
        $("#myText").text(function(e, text) {
          return text.replace('January', currentSelectedYear);
        });
        break;
      case 'test2':
        $("#myText").text(function(e, text) {
          return text.replace('January', 'mario');
        });
        break;
      case 'test3':
        $("#myText").text(function(e, text) {
          return text.replace('January', 'popyee');
        });
        break;
       }
  })
})

So when I click on farji once it changes my text but when click on again then it does not change please guide me how to solve this. Thanx in advance


1 Answers

Everyone's pointed out why it wont work a second time, but nobody's given you a solution.

Wrap 'January' in its own selector - you can then just set its text without having to worry about replace.

HTML:

<div id='myText'> hii farjiz calendar <span id="changeMe">January</span></div>

JS:

$('.farji').click(function(){    
    currentSelectedYear = $("#date_year option:selected").val();
    alert(currentSelectedYear);
    switch ($("#exams option:selected").val()) {
        case 'test1':
            $("#changeMe").text(currentSelectedYear);
            break;
        case 'test2':
            $("#changeMe").text('mario');
            break;
        case 'test3':
             $("#changeMe").text('popeye');
            break;
    }
});

For completion - your code always looks to replace the word 'January'. Once it's replaced the first time, the text no longer reads 'January', so replacing 'January' will have no effect.

like image 61
Dave Salomon Avatar answered Dec 16 '25 09:12

Dave Salomon