Friend
Friend

Reputation: 1346

Jquery dynamically enter values

below is my code

    <a href="#" onclick="$('#smiles_btn').click(); $('#chat_textarea').val($('#chat_textarea').val()+' :#').focus(); return false;"><img src="1.gif"></i></a>
    <a href="#" onclick="$('#smiles_btn').click(); $('#chat_textarea').val($('#chat_textarea').val()+' 8D').focus(); return false;"><img src="2.gif"></a>

as shown in the above code when user clicks on smiley image it changes the value of text area #chat_textarea values are different for different smiley images,above code works fine... but what if i have more then 100 smileys? is there any way i can change the value of chat_textarea dynamically...? because to load images Iam just for loop which loads all images 1 to given number...

Updated:Hi all I know that we can use classname

$('.add_smile').on('click', function(){
// Prepend the ALT of the image to the textarea
$('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});

But my question is different...i can not add alt / value to each image, it should be loaded automatically,something like fetching ;) from json file by passing id ....is there any ways to fix in that way....

Upvotes: 0

Views: 63

Answers (2)

Martijn
Martijn

Reputation: 16113

Below some simpeler html.
If you want to load them dynamicly, just use your language of choice to loop through an array:

// Php
foreach($smileys as $img=>$code){ echo '<img src="'.$img.'" alt="'.$code.'" />';}

// Javascript
$.each(smileys, funcion(index,smile){
   $('#smileWrap').append('<img src="'+smile.src+'" alt="'+smile.alt+'" />')
});

<img class="add_smile" src="/img1.jpg" alt=":)" />
<img class="add_smile" src="/img2.jpg" alt=":(" />
<img class="add_smile" src="/img3.jpg" alt=";)" />

$('.add_smile').on('click', function(){
    // Prepend the ALT of the image to the textarea
    $('#chat_textarea').val( $('#chat_textarea').val()+ this.alt );
});

jQuery doesnt care what you add the click to, the image is just fine. If you want a pointer as mouse, just css that.

Now you can use php to loop and place as many images as needed. Images are required to have an alt, that's fixed. And we can easily access it in javascript, not needing extra html (the anchor) to get that.

My jsFiddle, with auto space-add if not present

Upvotes: 1

Moshtaf
Moshtaf

Reputation: 4903

Remove unnecessary links, add a ClassName and a data-val attribute to each smiley and modify your HTML like this:

<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>
<img src="1.gif" class="smiles_btn" data-val=':#'>
<img src="2.gif" class="smiles_btn" data-val='8D'>

Then use this JQuery:

$('.smiles_btn').click(function(){
    $('#chat_textarea').val($('#chat_textarea').val() + ' ' + $(this).data('val')).focus();
});

Check JSFiddle Demo

Upvotes: 1

Related Questions