How can I set required attribute on a input field using javascript/jquery

 function validateForm(){
	var participants = document.getElementById('input_1_36_1').value;
	var shirts = document.getElementById('input_1_18').value;

	if(Number(participants) != Number(shirts)){
		
	
		$('#input_1_36_1').attr('required', true);
 	    $('#field_1_45').css('color','red');
		 $('#input_1_36_1').css('border','2px solid red');
		 $('#field_1_45').show();
		

		
	   }else{
		 
		 
		 $('#field_1_45').css('color','green');
		  $('#field_1_45').hide();
	   }

	
}
validateForm();

Please try the following code and let me know how that goes! :smile:

$(document).ready(function() {
  var participants = $('#input_1_36_1');
  var shirts = $('#input_1_18');
  var field = $('#field_1_45');

  function validateForm() {
    if (Number(participants.val()) !== Number(shirts.val())) {
      participants.attr('required', true);
      field.css('color', 'red');
      participants.css('border', '2px solid red');
      field.show();
    } else {
      field.css('color', 'green');
      field.hide();
    }
  }

  // Call validateForm every time the values of the input fields change
  participants.add(shirts).on('input', validateForm);

  validateForm();
});

Thanks for the help, your code is working far better than mine. Only the required attribute that does not work.

Please try the following code and LMK if that works.

$(document).ready(function() {
  var participants = $('#input_1_36_1');
  var shirts = $('#input_1_18');
  var field = $('#field_1_45');
  var form = $('#your_form_id');  // replace with your form's ID

  function validateForm() {
    if (Number(participants.val()) !== Number(shirts.val())) {
      field.css('color', 'red');
      participants.css('border', '2px solid red');
      field.show();
      return false;
    } else {
      field.css('color', 'green');
      field.hide();
      return true;
    }
  }

  // Call validateForm every time the values of the input fields change
  participants.add(shirts).on('input', validateForm);

  // Prevent form submission if validateForm returns false
  form.on('submit', function(event) {
    if (!validateForm()) {
      event.preventDefault();
    }
  });

  validateForm();
});

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.