-3

I am trying to use the data-required attribute according to data,if value == 1 I want to set the data-required attribute to true else false .

Html:

<input type="text" id="txtPhone" name="phone" data-required="true" class="form-control">

Javascript:

 var value = $("#txtPhone").val();
        if (value == "1") {
            $("#txtPhone").... // Set data required true for txtphone input
        }
        else {
            $("#txtPhone")... // Set data required false for txtphone input
        }

How can I set data-required to true or false?

How can i do this by JavaScript?

Sid M
  • 4,354
  • 4
  • 30
  • 50
user3722851
  • 147
  • 4
  • 13

2 Answers2

15

As far as i understand your question.. is this what you are looking for fiddle?

        var myvalue = $("#txtPhone").val();
        if (myvalue == "1") {
             $("#txtPhone").attr("data-required","true");
            alert(myvalue);
        }
        else {
           $("#txtPhone").attr("data-required","false");
            alert(myvalue);
        }
Sid M
  • 4,354
  • 4
  • 30
  • 50
2

Do it this way :

var value = $("#txtPhone").val();
if (value == "1") {
    document.getElementById('txtPhone').setAttribute("data-required","true");
}
else {
    document.getElementById('txtPhone').setAttribute("data-required","false");
}

Check out this fiddle.

PG1
  • 1,220
  • 2
  • 12
  • 27