Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable for jquery script

I dont know Javascript at all, so sorry for asking a question like this...

This is what I have:

$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});  
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...

So... Right now, my pages has 30 lines :)

Is there a way to do it less complicated?

Thanks!

like image 598
Tibby Avatar asked Dec 12 '22 06:12

Tibby


2 Answers

Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.

$(document).ready(function(){
         $("[id^='more']").click(function(){
                $("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
         });
});
like image 112
Sudharsan S Avatar answered Dec 25 '22 10:12

Sudharsan S


Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,

$(document).ready(function(){
    $("[id^='more']").click(function(){
      var index = $(this).attr('id').match(/\d+/)[0];
      $("#update" + index).slideToggle("normal");
    });
});
like image 41
Rajaprabhu Aravindasamy Avatar answered Dec 25 '22 10:12

Rajaprabhu Aravindasamy