Peter
Peter

Reputation: 99

Apply value to form field based on field label

I have a form field which has a label of "Campaign Source".

 <label id="tfa_249-L" for="tfa_249" class="label preField ">Campaign Source</label><br>
 <divclass="inputWrapper">
 <input type="text" id="tfa_49" name="tfa_249" value="" placeholder="" class="">
 </div>

Based on that label ("Campaign Source"), how would I give this particular form field a default value using jQuery?

Although its much easier to target the field based on it's ID, I wont always know the ID in advance whereas I do know the label and can set that myself.

Thanks in advance.

$('#tfa_249').val('<?php echo $_GET['utm_source']; ?>');

Upvotes: 0

Views: 53

Answers (4)

Jay Blanchard
Jay Blanchard

Reputation: 34416

You could test with :contains -

if( $("label:contains('Campaign Source')") ) {
    var forInput = $("label:contains('Campaign Source')").attr('for')
    $("label:contains('Campaign Source')").next('.inputWrapper').find('input[name="'+ forInput +'"]').val("<?php echo htmlspecialchars($_GET['utm_source']); ?>");
}

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

// Start by finding the label (based on text value)
$('label:contains("Campaign Source")')
  // grab the div next door
  .next('.inputWrapper')
  // then find the `<input>` within
  .find('input')
  // now assign its value
  .val('<?= $_GET['utm_source']; ?>');

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

Assuming no other label contains "Campaign Source", find the label like so:

var lbl = $("label:contains('Campaign Source'));

then get the ID of the input it labels:

var inpid = lbl.attr('for');

and set that input's value:

$('#' + inpid).val("<?php echo htmlspecialchars($_GET['utm_source']); ?>");

Upvotes: 2

Alex
Alex

Reputation: 7688

Mixing commas...

you have

$('#tfa_249').val('<?php echo $_GET['utm_source']; ?>');

it should be

$('#tfa_249').val("<?php echo $_GET['utm_source']; ?>");

And remember, that the php code, must be executed in a .php file.

Upvotes: 1

Related Questions