Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery use variable by name of divID

Just a quick question, that I cannot fathom out, hope you guys and girls can help.

I have a div (with ID) that when clicked opens a new div - great works well, what I really want is to "populate" the new div with predefined text based on the clicked div's ID. example:

<div class="infobox" id="help_msg1">Click me</div>

I may have say 3 (actually more but...) of these div's

This opens:

<div id="helpbox">text in here</div>

In/on my .js page I have doc ready etc then:

var help_msg1 ='text that is a help message'; var help_msg2 ='text that is another help message'; var help_msg3 ='text that is yet another help message';

Then

$('.infobox').live('click',function() {
 $('#helpbox').remove();
 $('label').css({'font-weight': '400'});
 $(this).next('label').css({'font-weight': '900'});
 var offset = $(this).next().next().offset();
 var offsetby = $(this).next().next().width();
 var leftitby = offset.left+offsetby+10;

$('body').append('text in here'); $('#helpbox').css( { 'left': leftitby, 'top': offset.top } ); });

Note I remove each #helpbox before appending the new one and the .next().next() identifies the appropriate text input that lot all works.

What I need is how do I put var help_msg1 into the append when id="help_msg1" is clicked or var help_msg2 when id="help_msg2" is clicked etc. I have tried

like image 329
Russell Parrott Avatar asked Nov 28 '25 00:11

Russell Parrott


1 Answers

One way would be to associate your help messages with the <div> elements themselves using jQuery's data() facility:

$(document).ready(function() {
    $("#help_msg1").data("help_msg", "text that is a help message");
    $("#help_msg2").data("help_msg", "text that is another help message");
    // etc...
});

Then later you can fetch the message directly from the clicked <div> element:

$(".infobox").live("click", function() {
    // ...
    $("body").append($(this).data("help_msg"));
});
like image 141
Frédéric Hamidi Avatar answered Nov 29 '25 17:11

Frédéric Hamidi



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!