0

I want to update an input of one field to be data attribute of another field. I manage to do it once, but doesn't work the second time.

$('button').click(function() {
$('[data-key="hello"]').attr('data-key', $('[data-id="hi"]').val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input data-id="hi">
<input data-key="hello">
<button>Click</button>

How do I make it update every time I click the button? Why doesn't it work every time?

2 Answers 2

2

You have use wrong approach. Because on every click data-key has been changed. You should use class or id.

$('button').click(function() {
$('#hello').attr('data-key', $('[data-id="hi"]').val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input data-id="hi">
<input id="hello" data-key="hello">
<button>Click</button>

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

Comments

0

You can use data() attribute to achieve it.

$('button').click(function() {
   $('#hello').data('key', $('#hi').val());
   
   console.log($('#hello').data('key'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input data-id="hi" id="hi">
<input data-key="hello" id = "hello">
<button>Click</button>

2 Comments

It seems like yours doesn't change at all when I inspect it. I found the problem, I was selecting the data attribute that already changed.
I've just updated my answer, please take a look at @Tom Bomb

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.