1

I want to change the required attribute of an HTML input if the value of another input is larger than 8. (without submitting anything)

<input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">

Basically if the value of inputCheck is larger than 8, set rquired of inputReact to true. I know how to change the attribute, problem is checking the value without submitting.

3 Answers 3

1

You can use the input listener

let checkBox = document.getElementById("inputCheck")
, textBox = document.getElementById("inputReact")

checkBox.addEventListener("input", evt => {  
  if(evt.target.value > 8) textBox.setAttribute("required", true)
  else textBox.removeAttribute("required")
})
<input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">

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

Comments

0

Add a change event listener to the required input field.

$('#inputCheck').change(function() {
    const value = $(this).val();
    const rInput$ = $('#inputReact');
    if(value > 8) { // could also use parseInt(value) to convert value into number if it isn't already.
        rInput$.attr('required', true); 
    } else {
        rInput$.removeAttr('required');
    }
});

2 Comments

cool, however you requested answer in jquery and accepted a pure JS answer :) just saying, no hard feelings.
It was the first one to come so I just accepted it, never posted before. I‘ve used yours though.
0

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>keydown demo</title>
 
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
 
<form>
 <input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">
</form>

 
<script>
var xTriggered = 0;
$(document).ready(function()
{
alert("ok");
$( "#inputCheck" ).keydown(function( event ) {

 var myLength = $("#inputCheck").val().length;

if((myLength+1) > 8)
{

$("#inputReact").attr("required","true");
}
});
 
});
</script>
 
</body>
</html>

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.