Patrick
Patrick

Reputation: 100

How to set an textbox / select as required - using JavaScript

I need to know how I can set a textbox or an select to "required".

This is how it looks

<input type="textbox" name="SAP Pers. Nr." type="text" size="30" value="">

And after the js it should look like this

<input type="textbox" name="SAP Pers. Nr." type="text" size="30" value="" required>

May someone can help me?

Upvotes: 0

Views: 7691

Answers (3)

user4128650
user4128650

Reputation: 1

in html:-

<form name="frm">
  Question: <input name="question"/> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question"/>
</form>

javascript:-

function IsEmpty(){
  if(document.forms['frm'].question.value == "")
  {`enter code here`
    alert("empty");
    return false;
  }

Upvotes: -2

putvande
putvande

Reputation: 15213

You could do this:

window.onload = function() { 
    document.getElementsByName('SAP Pers. Nr.').setAttribute('required','required');
}

https://developer.mozilla.org/en-US/docs/Web/API/Element.setAttribute

Upvotes: 2

Shryme
Shryme

Reputation: 1570

Add a onsubmit="return validateRequired() to your form, and in javascript you can do something like this:

function validateRequired()
{
    var textBox = document.getElementById('textBox');
    if (textBox.value == "")
        return false;
}

This will check if your textBox have a value, if no, it return false. You need to add an id to your textBox for the getElementById to work.

Upvotes: 1

Related Questions