0

I have a checkboxlist which is being binded from the database and Id of the checkbox is being binded with the help of data-bind attribute and when the user clicks the submit button I'm iterating through the checkboxlist and checking whether the Checkbox is checked on not, if it is checked then i want get the Id of the checkbox.

<input type="checkbox"  class='roles' name='roles' data-bind="attr: { value: Id }" />

This is how i tried

  if ($(this).is(':checkbox')) {
  if (this.checked)
  {
   var input = $(this);
   if ($(input).data().bind) {
    alert($(this).data('bind'));
  }
  }
 }

i actually want to get this value data-bind="attr: { value: Id }

But in the alertbox im getting message as data-bind="attr: { value: Id }, where as i want to get 1,2 etc

1
  • 1
    Note that after var input = $(this), input is already a jQuery instance. No need to then repeat the $() by doing $(input). It's harmless, but pointless. Commented May 28, 2014 at 11:48

3 Answers 3

4

But in the alertbox im getting message as data-bind="attr: { value: Id }, where as i want to get 1,2 etc

Right, the value of data-bind hasn't changed. If you want the value of the value attribute, you need to get that instead:

alert(input.val());

Live example:

var obj = {Id: "foo"};

ko.applyBindings(obj, document.body);
display("data-bind: " + $("input").data().bind);
display("value: " + $("input").val());

Side note: Knockout has a value binding for setting the value of a form control:

<input data-bind="value: Id">
Sign up to request clarification or add additional context in comments.

Comments

2

You have incorrect syntax to get data attribute. You need to use:

$(this).data('bind')

Refer to .data() Documentation

3 Comments

Actually, the given syntax works as well. If you call data with no arguments, you get back an object with the information stored on it as properties. This is about three-quarters of the way down the page you linked. Example: jsbin.com/zafakobe/1
im getting the message in the messagebox as data-bind="attr: { value: Id }
And in fact, the question was buried at the end of the question: The OP is getting the value of data-bind, just not the value they expected to get.
2

you can do this way:

var value = $(input).data("bind");

or this way:

var value =$(input).attr("data-bind");

4 Comments

True, but it doesn't answer the question of why what the OP's doing (which is valid) doesn't work.
im getting the message in the messagebox as data-bind="attr: { value: Id }
you mean data().bind() in valid?
@EhsanSajjad: Yes, .data().bind (no ()) is valid.

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.