So I've been having trouble understanding why my "document.getElementbyID()" function is breaking my external script. My script and html file look like this:
function validateRegCat(obj)
{
setRegCat(obj);
var invalid = false;
if(obj.value == "Invalid")
{
alert("Please select a Registration category")
invalid = true;
}
return invalid;
}
function setRegCat(obj)
{
if(obj.value == "UWSStudent")
{
document.getElementbyId("Institution").value = "The University of Western Sydney";
document.getElementbyId("Institution").readOnly = true;
}
}
<body>
<form class="Application" action"prac1task3Form.asp" method="post" onsubmit="return finalValidate(this);" >
<div class="PersonalDetails">
<fieldset>
<legend>
<h3>Personal Details</h3>
</legend>
<!--Kept in a list to keep the form looking neat and organised-->
<ul>
<li>
<!-- Create a selection box for the user to input their Registration Category-->
<label for="RegCat"><strong>Registration Category:</strong><sup>*</sup></label>
<select name="RegCat" size="1" onblur="validateRegCat(this); setRegCat(this)" required>
<option value = "Invalid">--Choose a registration category--</option>
<option value = "UWSStudent">UWS Student</option>
<option value = "OtherStudent">Student at another Institution</option>
<option value = "UWSAcademic">UWS Academic</option>
<option value = "UWSStaff">UWS Staff</option>
<option value = "OtherAcademic">Academic from another Institution</option>
<option value = "PublicMember">Member of the public</option>
<option value = "Retired">Retired</option>
</select>
</li>
<!-- Input Institution. Sets automatically to Uws and readonly if certain registration categorys are selected-->
<li>
<label for="Institution"><strong>Institution of learning/work:</strong> </label>
<input type="text" name="Institution" id="Institution" size="30" maxlength="30"/>
</li>
</ul>
</fieldset>
</div>
</form>
</body>
I've cut the html down to only the relevant parts. What I want the script to do is to change the value of the "Institution" text input to read only and set the text displayed. However I've found that the "document.getElementbyId("Institution")" breaks the script. The script runs fine before that and when I change those lines to meaningless things such as alerts, the script functions and returns as it should.
I assume the problem is related to typos (make sure you have capital 'B' instead of 'b'): document.getElementById (https://developer.mozilla.org/it/docs/Web/API/Document/getElementById).
If you use Firebug (http://getfirebug.com/) or similar while developing you can detect these small errors easily.
Related
I have created with javascript and I get a result of a string.I get that result on my html code
<div id="results"></div>
Next,I want when I select for example Red to check if it is the the same thing (string), the select option - > Red with the string of this code
<div id="results"></div>
I was trying to do it but I failed.It is not working not even sure ,if I press the submit button I will send the string.
<div id="results"></div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="submit" value="results"/>
It appears that you want to check whether the selected option is equal to the text value of the div #results. You can achieve this effect like so:
$(document).ready(function(){
var select = $("select");
$("input[type=\"button\"]").click(function(){
var text = select.find(":selected").text();
if(text==$("#results").text()){
$("#results").html(text+" is equal!");
}else{
$("#results").html(text+" is not equal :(");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results">Red</div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="button" value="results"/>
</form>
A form is going to be Sending data somewhere, it would be best to remove the form, leaving the select and button elements. In the button add the code onclick='myFunction() ; when the button is clicked it will run the javascript function called myFunction(). Also you need to give the select a Id. I'm using selectInput
<script>myFunction() { document.getElementById('result').innerHTML = document.getElementById('selectInput').value;} </script>
Now when ever the button is pressed it will set the content of the div equal to the value entity in the selected select box option
You lack an action attribute.
<form method="post" action="path/to/file">
<select name="select">
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input type="submit" value="Get Results" />
</form>
Use a function, and a regular button. No form is needed.
<button onclick='func()'></button>
const func = () => {...}
I'm trying to validate a select menu I have on my page. If the first option is selected(the one with no value)and clicks the submit button, then I want to either display a span next to the menu or display the span under the menu. The span should tell the user to select an option (male/female). I'm having trouble doing either of these things. Is span not the correct thing to use here?
Note on possible duplicate: I read some of the answers posted on Stack similar to this question but some used JQuery which I have not learned yet. There was one answer that used Javascript which I tried to follow. It used a function with parameters and errorPlacement but I was having trouble understanding it and wanted to do it in a simpler way. There were other questions I looked as well, but I'm listing one for now.
Here is the link to the question: Problem with display error message in span element when validation
Also I'd specially like to use span tags if possible then prepend & append.
Here is my code:
HTML
<form onsubmit="return Validate();">
<div id="div1">
<select id="gender">
<option value="">Select gender:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input type = "submit" value="submit"/>
</form>
JAVASCRIPT
function Validate() {
var gender = document.getElementById("gender");
if (gender.value == "") {
var gendererror = document.createElement("span");
gendererror.innerHTML = "please select a gender";
return false;
}
return true;
}
I think this is what you want. Always have a error-msg div to give styles to your errors.
function Validate() {
var gender = document.getElementById("gender");
if (gender.value == "") {
if(!document.getElementById("error-msg").childNodes.length){
var gendererror = document.createElement("span");
gendererror.innerHTML = "please select a gender";
document.getElementById("error-msg").appendChild(gendererror);
}
return false;
}else{
return true
}
}
<form onsubmit="return Validate();" action="#">
<div id="error-msg"></div>
<div id="div1">
<select id="gender">
<option value="">Select gender:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input type = "submit" value="submit"/>
</form>
<script type="text/javascript" src="./jsfile.js"></script>
I think why you didn't get error message is because, javascript is confuse where to put the created tag and its content. You might have forgot to appendChild with some tag, so that javascript knows where to put created tag
Html:-
<form onsubmit="return Validate();">
<div id="div1">
<select id="gender">
<option value="">Select gender:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<input type = "submit" value="submit"/>
</form>
Just below, Script:-
function Validate() {
var gender = document.getElementById("gender");
if (gender.value == "") {
var relationshiperror = document.createElement("span");
document.body.appendChild(relationshiperror); // You can add to any new div for example, also after submit button
relationshiperror.innerHTML = "Please select the type of relationship";
return false;
}
return true;
}
I am trying to create what I hope is a somewhat simple donation form. There are two options to choose from:
A drop down with a text field to enter an amount
A text field to write in an other designation along with a text field to enter an amount
I've been looking through a lot of different examples of code, but I'm not entirely sure how to search the technical name for what I need. I need to have an alert appear when nothing is entered as well as an alert when only one part of 1 or one part of 2 is entered. I know this is something I need JS for, but have zero experience with it.
I found several pages that were a little helpful with validation and alert messages for multiple fields, but I think I need to have an either/or type of alert (if that makes sense). EITHER you choose from the drop down and enter an amount OR you enter something in the "Other" text field and enter an amount.
You can see my code below. I included some JS I found and tried to modify that seemed to be closest to what I'm looking for, but with my limited knowledge of the language I know it's not correct (try not to judge me). I can get an alert message that works sometimes and not for everyone. And sometimes the alert still appears when it's filled out correctly.
I feel like my brain is fried at this point, so any help you can provide is greatly appreciated. Javascript is definitely going to the top of my "Must Learn" list after this. Thank you!
<script>
function validateForm() {
var x = document.forms["form1"]["FUND1"].value;
var x = document.forms["form1"]["FUND2"].value;
var x = document.forms["form1"]["GIFT_AMOUNT1"].value;
var x = document.forms["form1"]["GIFT_AMOUNT2"].value;
if (form1.FUND1.value == '' && form1.FUND2.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
if (form1.GIFT_AMOUNT1.value == '' && form1.GIFT_AMOUNT1.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
}
</script>
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="0.00"/>
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation"/>
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="0.00"/>
</div>
<div style="clear:both; float:left;">
<p><input type="submit" value="Continue" class="continue_button" onclick="validateAndSend()"></p>
</div>
What you are doing is ok.
To improve what you are doing you can try this:
I'm paring FUND and GIFT_AMOUNT because I guess is what you are trying to do, now the alert will show when both 1s or 2s are empty.
function validateForm() {
var form1 = document.forms['form1']
if (form1.FUND1.value === '' || form1.GIFT_AMOUNT1.value === '') {
alert("please select a donation designation and an amount 1.");
return false;
}
if (form1.FUND2.value === '' || form1.GIFT_AMOUNT2.value === '') {
alert("please select a donation designation and an amount 2.");
return false;
}
return true;
}
In your form you need to initialize your GIFT_AMOUNT inputs with value="" otherwise if you compare '0.00' with '' always will be false.
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="" />
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation" />
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="" />
</div>
<div style="clear:both; float:left;">
<p>
<input type="submit" value="Continue" class="continue_button" />
</p>
</div>
</form>
There is no need to call a function in your onclick property because you are calling the submit function already to improve this behavior you can do something like this:
function submitForm() {
if (validateForm()) {
// do some stuff
}
}
and change the onsubmit property from your form
<form ... onsubmit="submitForm()">
If you are starting with javascript will be a good idea to learn how to use the console in order to debug your scripts. This article is a good point to start and as a last tip check this out.
I have a text input, alongside I have option tag with two options.
Basically I want to save the text that the user enters while switching between options, but if the user choose an option that he already enterd a text the text should appear in the input field as the default value.
And of course it's part of the submit form.
Many thanks in advance!
<div>
<p>please enter your description for each of the languages</p>
<input id="description" type="text">
<select id="language-select">
<option value="EN">EN</option>
<option value="FR">FR</option>
</select>
</div>
You can use local storage for this if you want to persist what is saved, otherwise a variable would be good enough.
Example with variable
var previous;
var state = {};
$("#language").on('focus', function() {
previous = $(this).val()
}).change(function() {
state[previous] = $("#test").val();
$("#test").val('');
if (typeof(state[$(this).val()]) != 'undefined') {
$("#test").val(state[$(this).val()]);
}
$("#test").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="test" id="test" />
<select id="language">
<option val="en">EN</option>
<option val="fr">FR</option>
</select>
</form>
I'm trying to redirect to a page based on the selected option, but with javascript validation.
I have this form:
<form action="verify.php" method="post">
<label for="class_year" class="inner_text">Year Range</label>
<select id="class_year" name="year">
<option value="a">50</option>
<option value="b">60</option>
<option value="c">70</option>
<option value="c">80</option>
<option value="c">90</option>
</select>
<label for="dob" class="inner_text">Date of Birth (YY-MM-DD)</label>
<input name="dob" type="text" class="false" id="dob" maxlength="10">
</form>
Now I have this verify.php file that redirect for example to a.html if you choose 1950:
<?php
header('Location: '.$_POST['year'].'.php');
?>
What I want to do is to verify what my visitors choose. For example if you write 51-02-28 in text box, that mean you must choose 1950, so you will be redirected to a.html; if you write for example 61-02-28 but you choosed 1950 then you can't submit the form an a alert will show. And if you write anything else for example 41-02-29, then you will be alerted too and the form will not be submited. The first 2 option redirect to a.html and b.html, the last 3 options redirect to the same page c.html .
In conclusion I need to validate only the first number from the text box. I don't know how to do that with javascript!
I apreciate any and all comments, thank you.
You can go ahead with validation by using normal javascript and while redirecting you can use something like this instead of PHP redirect
Your code should be something like this:
<form action="verify.php" method="post" id="mainForm">
<label for="class_year" class="inner_text">Year Range</label>
<select id="class_year" name="year">
<option value="50">50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
</select>
<label for="dob" class="inner_text">Date of Birth (YY-MM-DD)</label>
<input name="dob" type="text" class="false" id="dob" maxlength="10">
</form>
<script type="text/javascript">
$("#mainForm").submit(function(){
var yearVal = $("#dob").val().split("-")[0];
var redirectObj= [
['50','a'],
['60','b'],
['70','c'],
['80','c'],
['90','c']
];
if(parseInt(yearVal)>parseInt($("#class_year").val()) && parseInt(yearVal)<(parseInt($("#class_year").val())+10))
{
var redirectPage = "";
redirectObj.forEach(function(entry) {
if(parseInt(entry[0])==(Math.round(parseInt(yearVal)/10))*10)
{
redirectPage = entry[1];
}
});
window.location = redirectPage+".php";
}
else
{
alert("you have entered invalid value");
return false;
}
});
In case you want to redirect it to the first letter of the textbox you can use something like this
window.location = $("#dob").val().charAt(0)+".php";
You may check the working code at http://jsfiddle.net/amanchhabra1990/Uy78a/
Please let me know if this helps you.