Aleks Per
Aleks Per

Reputation: 1639

Jquery set value to input field based on attribute

I have input field like:

<input data-checkout="card-number" type="tel" placeholder="card number" autocomplete="off" class="input-control" value="">

How I can set a value of this field with jquery? How to get data-checkout="card-number" and set value ?

Upvotes: 1

Views: 1677

Answers (5)

Berthur
Berthur

Reputation: 4495

It depends on what you wish to access it by. To access the element, you can use, for example:

$('.input-control')  // Finds all elements with this class

or

$('.input-control[data-checkout=card-number]')  // Finds all elements with this class and this data-checkout value

or some other selector, depending on your application. Then, to set the value you can do:

$(/* your selector */).val('some value'); // Sets the value to 'some value'

and to get the value fo data-checkout:

$(/* your selector */).data('checkout');  // Returns 'card-number'

It is somewhat unclear what exactly you are looking for, but hopefully some of this answers your question.

Upvotes: 2

hasen2009
hasen2009

Reputation: 39

$('input[data-checkout="card-number"]').val('here') // replace word (here) with the value you want

Upvotes: 0

Ph0b0x
Ph0b0x

Reputation: 674

in jquery you can use any attribute as a selector using this format:

$('[your-attr="attr value"]')

Answering your question this should work:

$('[data-checkout="card-number"]').val("Your val"); 

Upvotes: 2

dreamHatX
dreamHatX

Reputation: 487

You can use basic Javascript to set the value.

for(i=0; card=document.querySelectorAll("input[data-checkout=card-number]")[i]; i++){
    card.value="sample value";
} 

Upvotes: 1

Mart&#237;n Zaragoza
Mart&#237;n Zaragoza

Reputation: 1817

Using jquery you could use the val function:

$(".input-control").val("Some value")

Using javascript:

document.querySelector(".input-control").value="Some value"

You could get the attribute by:

$(".input-control").attr("card-number")

Then you can do

$(".input-control").val($(".input-control").attr("card-number"))

Hope this helps

Upvotes: 1

Related Questions