0

I currently have a tag that looks like this:

<input name="code" type="text" />

I wish to leverage JQuery to add text inside this tag e.g.

<input name="code" type="text" data-hj-whitelist />

The reason for this is Hotjar whitelisting with the data-hj-whitelist addition.

This is my current code, which I am aware will not work as I'm adding a class of which data-hj-whitelist is not. Other functions that sprung to mind e.g. add, append etc, add after the tag is closed. I need to add text inside the tag itself.

//WordPress Format
jQuery(document).ready(function( $ ) {
    //Obviously won't work as I'm not adding a class
    $('input').addClass('colin');
    //Console log to know the script fired  
    console.log('fired');
});

2 Answers 2

1

You should be able to do just:

$('input[name="code"]').attr('data-hj-whitelist','')
Sign up to request clarification or add additional context in comments.

Comments

0

If I understand your question correctly, you just want to add a data attribute to an input. You may do so like this:

$('input[name="code"]').attr("data-hj-whitelist","");

If needed, you may retrieve the value of a data attribute like this:

// Notice that the data- prefix is removed
$('input[name="code"]').data("hj-whitelist");

// You may also get the value using attr()
$('input[name="code"]').attr("data-hj-whitelist");

Example

// Set with attr(), retrieve with attr()
$('input[name="code"]').attr("data-hj-whitelist", "foo1")
console.log($('input[name="code"]').attr("data-hj-whitelist"));

// Set with attr(), retrieve with data()
$('input[name="code"]').attr("data-hj-whitelist", "foo2")
console.log($('input[name="code"]').data("hj-whitelist"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="code" type="text" />

3 Comments

For real? Drive-by down vote for the correct answer?
What's the logic in downvoting this answer and upvoting mine?
Thank you for both your input, appreciated it.

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.