0

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!

1
  • You don't need the if statement at all -- it's a no-op. Commented Oct 8, 2013 at 19:25

3 Answers 3

2

.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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thx for your quick and usefull explaination. Unfortunately your code doesn't work. I forgot to mention that there's another input field before the button. Therefore "next" doesn't work??
.next().next('.button') ? @JaapVermoolen
0

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>');
}

Comments

0

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.

Comments

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.