Iago Rif
Iago Rif

Reputation: 11

Jquery selectors updates with script

Sorry for my bad engl.

I have created a menu using the ajax calls, my only problem is that I can not operate one jquery script that I can riassumente in 4 lines:

 var lang='#de';
$(lang).on("click", function(){
    if($(this).attr('id')=='de')lang="#en";
    else lang = "#de";
    $("#testo").text(lang);	

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="en" value="test en" />
<input type="button" id="de" value="test de" />
 <div id='testo'></div>

As you can see the variable inserted in place of the selector does not update. I also tried in various ways using the document ready but nothing, none of it to update itself. Can you help me?

Upvotes: 1

Views: 35

Answers (3)

james_bond
james_bond

Reputation: 6908

Use both selectors ids de and en

var lang = 'de';
$(".language-sel").on("click", function(){
    lang = $(this).attr("id");
    $("#testo").text(lang);	
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="language-sel" type="button" id="en" value="test en" />
<input class="language-sel" type="button" id="de" value="test de" />
<div id='testo'></div>

Upvotes: 1

Kit
Kit

Reputation: 742

You can achieve what you want by including multiple comma separated items in your jQuery selector, as follows.

var lang='#de, #en';

$(lang).on("click", function(){
    if($(this).attr('id')=='de')lang="#en";
    else lang = "#de";
    $("#testo").text(lang);	

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="en" value="test en" />
<input type="button" id="de" value="test de" />
 <div id='testo'></div>

Upvotes: 0

Curiousdev
Curiousdev

Reputation: 5788

Even you can add same class to both button and than bind click event on class please find below snippet for more info

var lang='#de';
$(".clsbtn").on("click", function(){
  debugger;
    if($(this).attr('id')=='de')
      {lang="#en";}
    else {lang = "#de";}
    $("#testo").text(lang);	

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="en" value="test en" class="clsbtn"/>
<input type="button" id="de" value="test de" class="clsbtn"/>
 <div id='testo'></div>

Upvotes: 0

Related Questions