1

I have a form that calculates the sum of several input values (checkboxes and dropdowns - not user entered values). At the bottom of the form I have a "Discount Code" box, I want to be able to enter a code and it takes a set amount off the total.

With my code I am trying to say, if text entered = discount code, change the value of the input to 50. Here is what I have so far

var discountCode = 'DISTR50';
var codeEntered = $("input[name='discount']");

 if (discountCode = codeEntered) {
    $('#discount input').attr('value',50);
 }

and for the html:

<input type="text" id="discount" name="discount" class="txt"/>

5 Answers 5

5
if (discountCode == codeEntered) {
    $('input#discount').attr('value',50);
 }

Do not use = use either == or better ===

Also instead of using attr you can simple use val as suggested below and use input#discount as the correct selector and use val() to get the value


var discountCode = 'DISTR50';
var codeEntered = $("input[name='discount']").val();

 if (discountCode == codeEntered) {
    $('input#discount').val('50');
 }

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

Comments

1

= is assignment, == or === is to check if something is equal to the other.

What is it you want to fetch from $("input[name='discount']")? Cause this will give you a jquery object, try $("input[name='dicount']").val(); to fetch value, ie something like:

if('DISTR50' == $("input[name='discount']").val()){
    $("#discount input").attr("value", 50);
}

Comments

1

Just a couple of minor issues...

var discountCode = 'DISTR50';
var codeEntered = $("#discount").val();

if (discountCode == codeEntered) {
    $('#discount').val(50);
}

Notice I added .val() to to get and set values of inputs, and changed the if statement to use == instead of =.

I also used the ID of the input element, as this will be quicker than looking for an input by name.

Comments

0

Try this

var discountCode = 'DISTR50';
var codeEntered = $("input[name='discount']");

 if (discountCode === codeEntered) {
    $('#discount').val('50');
 }

Comments

0

You can't compare object with values

You need to do like this:

var discountCode = 'DISTR50';
var codeEntered = $("input[name='discount']").val(); <-- .val()

The code you are writing returns object in codeEntered variable, you should use .val() to get the value of that object.

And for the comparision use == or === (for strict comparison)

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.