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>
3
  • May it be jQuery? - Possible duplicate of stackoverflow.com/questions/710275/… Commented Apr 23, 2014 at 4:50
  • Yes, I should have mentioned im trying to do this using jquery but im stuck solving this seemingly basic procedure. Commented Apr 23, 2014 at 4: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). Commented Apr 23, 2014 at 4:53

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.