2

Hi i am writing a php based code in which i am generating checkbox with different id and name

<input type="checkbox" name="settle_check[]" id="settle_check['.$res2['id'].']" value="1" onclick="calculate_discount(\''.$res2['id'].'\');"/>

and my function of calculate discount is as follow

 function calculate_discount(id){
    alert($('#settle_check['+id+']').val());
    if($('#settle_check['+id+']').is(":checked")){
        alert('Hiii');
    }
    else{
        alert('Byeee');
    }
}

now for every time it is not capturing the value and giving alert of undefined. Please Help me.

3 Answers 3

3

You are using [] in ID selector which are meta characters. You need to escape them.

Use

$('#settle_check\\['+id+'\\]').val()

Docs

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.

OR

You can use Attribute Equals Selector [name="value"]

$('[id="settle_check[' + id +']"]').val()
Sign up to request clarification or add additional context in comments.

Comments

1

Use this

$('#settle_check\\['+id+'\\]').val()

Comments

1

You can also try this:

Instead of passing the id, pass the element itselfe like:

<input type="checkbox" name="settle_check[]" value="1" click="calculate_discount(this);"/>

and update the function to:

function calculate_discount(element){
    alert($(element).val());
    if($(element).is(":checked")){
        alert('Hiii');
    }
    else{
        alert('Byeee');
    }
}

With this solution you avoid unnecessary jQuery searching.

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.