0

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>
quatchis
  • 63
  • 1
  • 6
  • May it be jQuery? - Possible duplicate of http://stackoverflow.com/questions/710275/how-to-add-update-an-attribute-to-an-html-element-using-javascript – toesslab Apr 23 '14 at 04:50
  • Yes, I should have mentioned im trying to do this using jquery but im stuck solving this seemingly basic procedure. – quatchis Apr 23 '14 at 04:51
  • You simply assign to the div's *data-foo* attribute. How you reference the div is up to you, but along the lines of: `div.setAttribute('data-foo',textarea.value)`. – RobG Apr 23 '14 at 04:53

3 Answers3

1

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.

DoctorLouie
  • 2,699
  • 1
  • 18
  • 23
0

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)
Prabhat Jain
  • 346
  • 1
  • 8
0

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.

yeshansachithak
  • 832
  • 2
  • 18
  • 34