quatchis
quatchis

Reputation: 63

Change HTML5 data attribute when updating an input field

I'm trying to use some javascript to update a data-attribute (data-foo) associated with a div when entering text into an input field. Any ideas? I'm totally stumped.

<div data-foo=""></div>
<textarea name="extraoptions">bar</textarea>

Upvotes: 0

Views: 480

Answers (3)

yeshansachithak
yeshansachithak

Reputation: 840

I just code for you in my FIDDLE. Use this JSFIDDLE. It will work properly. I hope this is the one you want now.

HTML5

<input id="text" type="text"/>
<br/><br/>
<div id="result" data-foo="">This is the div with `data-foo` attribute. While you typing this div `data-foo` attribute will change as input valu. If you want to check it. Just click on below button.</div>
<br/>
<button id="test">What is my DIV `data-foo` now?</button>

jQuery

//FOR TESTING - This function will help you to test the below function is working or not
$("#test").click(function(){
    var value = $('#result').attr('data-foo');
    alert(value);
});

//This function will auto change `data-foo` while you typing 
$("#text").keyup(function(){
   var text = $(this).val();
   $("#result").attr('data-foo',text);
});

Use it when DOM is ready.

If you need my help. Please find me any of social network by searching yeshansachithak.

Upvotes: 0

DoctorLouie
DoctorLouie

Reputation: 2674

With jQuery you could do something like this:

jQuery("body").find("div[data-foo]").html('My New HTML Content For DIV with data-foo attribute');

So, why use:

jQuery("body")

Opposed to:

$("body")

You may ask? Well, this makes sure we don't get any conflicts with any other libraries that might be in use on a site, consider it a safe way of writing jQuery.

Upvotes: 1

Prabhat Jain
Prabhat Jain

Reputation: 346

If you can get this div by id or by class, lets say

<div id="div1" data-foo=""></div>

then you can do this -

$("#div1").attr("data-foo", val)

Upvotes: 0

Related Questions