Meules
Meules

Reputation: 1389

Replace content if input has value

When an hidden input has a value that contains the letters "LO" I want to replace a button inside a form with some different html.

HTML:

<input type="hidden" name="LO123456" id="hiddenCode" value="LO123456" />
<input type="text" name="quantity" id="formProductQuantity" value="1" />
<a class="button green" href="#" onclick="$('#form').submit(); return false;">Add to cart</a>

So in above example the hidden field has "LO" in it, so how can I replace the button with

<a class="button green" href="some.html">More information</a>

What I tried:

if ($( "input[value*='LO']" ).find('.button').replaceWith('<a class="button green" href="some.html">More information</a>'));

That doesn't work though because it replace also the buttons without "LO" in the hidden field.

Any help greatly appreciated!

UPDATED

I've updated the code because there's another input field which I didn't mentioned!

Upvotes: 0

Views: 97

Answers (3)

l2aelba
l2aelba

Reputation: 22167

.find('.button') to .next('.button')

.find() = find element inside this element

.next() = find element next to this element


Use $( "input[value^='LO']")(input starts with LO)


You don't need to use if else statement


Add :hidden for more focusing

or use your input id hiddenCode (if you are sure it unique id)


Finally :

var newButton = '<a class="button green" href="some.html">More information</a>';
$("input:hidden[value^='LO']").next('.button').replaceWith(newButton);

Using ID

var newButton = '<a class="button green" href="some.html">More information</a>';
$("#hiddenCode").next('.button').replaceWith(newButton);

Upvotes: 2

R. Oosterholt
R. Oosterholt

Reputation: 8080

The if statement is not needed in: if ($( "input[value*='LO']" )....

You need next instead of find:

$( "input[value^='LO']" ).next('.button').replaceWith('<a class="button green" href="some.html">More information</a>');

Next searches for the next sibling, find searches for descendents.

Upvotes: 0

Alex
Alex

Reputation: 1593

Use something like:

var v = $('#hiddenCode').val();
if (v && v.indexOf('LO') > -1) {
  $('.button').replaceWith('<a class="button green" href="some.html">More information</a>');
}

Upvotes: 0

Related Questions