Fiddle works but test page doesn't (missing .ready handler) - javascript

I have a problem, I want to show some specific field when i select a specific radio button. I did that and I test on this page (http://jsfiddle.net/niklakis/cw0qLnk5/5/) but when i get the code (which is the below) it does not show the specific fields when I select the radio button.
Can you help me please?
THIS IS THE WHOLE CODE ....
<html>
<head>
<script src="jquery-1.11.2.min.js"></script>
<script>
$("input[type='radio']").change(function () {
if ($(this).val() == "Doctor") {
$("#DoctorRegister").show();
} else {
$("#DoctorRegister").hide();
}
if ($(this).val() == "Patient") {
$("#PatientGM").show();
$("#PatientGF").show();
$("#PatientAge").show();
$("#SelectDisease").show();
$("#Male").show();
$("#Female").show();
$("#Age").show();
$("#Disease").show();
} else {
$("#PatientGM").hide();
$("#PatientGF").hide();
$("#PatientAge").hide();
$("#SelectDisease").hide();
$("#Male").hide();
$("#Female").hide();
$("#Age").hide();
$("#Disease").hide();
}
});</script>
</head>
<body>
<fieldset>
<legend>Registration Form</legend>
<label>First Name
<input type="text" name="fname" required="required" />
</label>
<br/>
<br/>
<label>Last Name
<input type="text" name="lname" required="required" />
</label>
<br />
<br />
<label>Username
<input type="text" name="username" required="required" />
</label>
<br />
<br />
<label>Email
<input type="text" name="email" required="required" />
</label>
<br />
<br />
<label>Password
<input type="text" name="password" required="required" />
</label>
<br/><br/>
User Type:
<br/>
Doctor <input type="radio" name="answer" value="Doctor" />
Patient <input type="radio" name="answer" value="Patient" />
<br/>
<br/>
<input style="display:none;" type="text" name="DoctorRegister" id="DoctorRegister" />
<br/>
<br/>
<label style="display:none;" id="Male">Male</label>
<input style="display:none;" type="radio" name="PatientGM" value="male" id="PatientGM">
<label style="display:none;" id="Female">Female</label>
<input style="display:none;" type="radio" name="PatientGF" value="male" id="PatientGF">
<br/>
<br/>
<label style="display:none;" id="Age">Age:</label>
<input style="display:none;" type="text" name="PatientAge" id="PatientAge" />
<br/>
<br/>
<label style="display:none;" id="Disease">Disease:</label>
<select style="display:none;" id="SelectDisease">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<br/>
<br/>
</fieldset>
</body>
</html>

You're executing your code before the document is rendered. Either:
Move your code to the end of the document before the closing body tag or
Put your code in a document ready handler in the head like:
$( document ).ready(function() {
// your code here
});
jsFiddle example

$("input[type='radio']").change() will fire for all inputs of type radio button. So, try with:
$("input[type='radio'][name='answer']").change()

Related

required attribute is not working. (html)

I'm making a signup page using HTML and javaScript and it was working fine until I added a function to take the user to the next page, the problem is, if the textboxes where blank and I click on the button, it sends him to the next page instead of showing a validation error to fill them out.
here is the code of the function:
function signup() {
window.location.replace("file:///C:/Users/hb/Desktop/web%20project/afterlogin.html");
var userid = document.getElementById("username").value;
alert("Welcome " + userid);
}
here is the html code for the form:
<form method="post" class="info">
<p>
<label for="username">Username:</label>
<input type="text" id="username" minlength="6" maxlength="18" required /><br /><br />
</p>
<p>
<label for="email">E-mail:</label>
<input type="email" id="email" required /><br /><br />
</p>
<p>
<label for="password" required> Password:</label>
<input type="password" id="password" minlength="10" maxlength="18" required /><br /><br />
</p>
<p>
<label for="confirmpass">Confirm password:</label>
<input type="password" id="confirmpass" minlength="10" maxlength="18" required /><br /><br />
</p>
<p>
<label for="gender">Gender:</label>
<select id="gender">
<option id="male"> Male </option>
<option id="female"> Female </option>
</select><br /><br />
</p>
<p>
<label for="age">Age:</label>
<select id="age">
<option id="young">Young(12-18 years old) </option>
<option id="youth">Youth(19-40 years old) </option>
<option id="old">Old(more than 40 years) </option>
</select><br /><br />
</p>
<div class="terms">
<p>
<input type="checkbox" id="terms" checked="checked" required />
<label for="terms" id="terms">Agree to terms and conditions </label> <br />
</p>
</div>
<button id="button" class="signUpButton" name="SIGN UP" type="submit" onclick="signup();">SIGN UP</button> <br /><br /><br /><br />
<p class="outerAlt">Have an account already?</p>
<p class="alt">SIGN IN</p>
</form>
Instead of listening for a click on the button, listen for the form submission event
eg:
<form onsubmit="signup()">
required attribute stops the form from submitting if the field is empty, it does not stop arbitrary event handlers from changing the page.
If you want to only call your signup when the form is valid make it a form submit handler instead of a button click handler.
<form method="post" class="info" onsubmit="signup();return false;">
...
<button id="button" class="signUpButton" name="SIGN UP" type="submit">SIGN UP</button>
Attribute required is activating when you submit the form. You can click on any button or input inside the form, call event onclick, but it won't be submiting the form. To handle the event of submiting, you have to add onsubmit to your <form> elements and on the code below. Note, that the form submit will reload the page. To avoid this, you have to prevent default behavior by adding event.preventDefault().
function signup(event) {
event.preventDefault();
var userid = document.getElementById("username").value;
alert("Welcome " + userid);
}
<form method="post" class="info" onsubmit="signup(event)">
<p>
<label for="username">Username:</label>
<input type="text" id="username" minlength="6" maxlength="18" required /><br /><br />
</p>
<p>
<label for="email">E-mail:</label>
<input type="email" id="email" required /><br /><br />
</p>
<button id="button" class="signUpButton" name="SIGN UP" type="submit">SIGN UP</button>
</form>
onclick event will call the function when the button is clicked without validating the form. onsubmit event is called after the form is ready to submit (After the validation)
And you can use event.preventDefault(It will stop the page reloading after the submit. More About it) to instead of using return false;
function signup(event){
event.preventDefault();
}
document.getElementById().addEventListener("submit", signup);
Add addEventListener("submit", signup); to call the function onsubmit
Ex: document.getElementById("form1").addEventListener("submit", functionName);
Ex 2:
document.getElementById("form1").addEventListener("submit", function(){
// Code
});
function signup(event) {
event.preventDefault(); location.replace("LOCATION");
var userid = document.getElementById("username").value;
alert("Welcome " + userid);
}
document.getElementById("form1").addEventListener("submit", signup);
<form method="post" id="form1" class="info" data-registerForm>
<p>
<label for="username">Username:</label>
<input type="text" id="username" minlength="6" maxlength="18" required /><br /><br />
</p>
<p>
<label for="email">E-mail:</label>
<input type="email" id="email" required /><br /><br />
</p>
<p>
<label for="password" required> Password:</label>
<input type="password" id="password" minlength="10" maxlength="18" required /><br /><br />
</p>
<p>
<label for="confirmpass">Confirm password:</label>
<input type="password" id="confirmpass" minlength="10" maxlength="18" required /><br /><br />
</p>
<p>
<label for="gender">Gender:</label>
<select id="gender">
<option id="male"> Male </option>
<option id="female"> Female </option>
</select><br /><br />
</p>
<p>
<label for="age">Age:</label>
<select id="age">
<option id="young">Young(12-18 years old) </option>
<option id="youth">Youth(19-40 years old) </option>
<option id="old">Old(more than 40 years) </option>
</select><br /><br />
</p>
<div class="terms">
<p>
<input type="checkbox" id="terms" checked="checked" required />
<label for="terms" id="terms">Agree to terms and conditions </label> <br />
</p>
</div>
<button id="button" class="signUpButton" name="SIGN UP" type="submit">SIGN UP</button> <br /><br /><br /><br />
<p class="outerAlt">Have an account already?</p>
<p class="alt">SIGN IN</p>
</form>

Use JQuery to hide and show a div based on drop down selection

I'm trying to make a dropdown box hide and show a particular set of divs (ofwhich the class and the id are identical).
The values of the drop down correspond to the the name of the divs
My Attempt:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#submissionType").change(function () {
var submission = $(this).val();
if ($(this).val()) {
$("#"+submission).show();
} else {
$("#"+submission).hide();
}
});
});
</script>
html:
<select id="submissionType">
<option>Choose Submission Type</option>
<option value="member-submission">member-submission</option>
<option value="researcher-submission">researcher-submission</option>
<option value="student-submission">student-submission</option>
<option value="paper-submission">paper-submission</option>
</select>
<div class ="new-member-background">
<div class ="member-submission" id="member-submission">
<form action="SubmitData.php" method="post">
<input type="text" name="first" placeholder="First Name" />
<br/>
<input type="text" name="last" placeholder="Last Name" />
<br/>
<input type="text" name="title" placeholder="Title" />
<br/>
<input type="text" name="institution" placeholder="Institution" />
<br/>
<input type="number" name="dept_code" placeholder="Department Code" />
<br/>
<input type="text" name="division" placeholder="Division" />
<br />
<input type="text" name="email" placeholder="Email" />
<br/>
<input type="text" name="website" placeholder="Website" />
<br/>
<button type="submit" name="submit">Sign Up</button>
</form>
</div>
/**...Other divs...*/
</div>
You should hide them all and then reveal the selected one. EG:
$(function () {
//hide them all to begin with. It would be easier if they all shared a classname. You could also do this in CSS)
$("#member-submission, #researcher-submission, #student-submission, #paper-submission").hide();
//on change
$("#submissionType").change(function () {
var submission = $(this).val();
//hide them all:
$("#member-submission, #researcher-submission, #student-submission, #paper-submission").hide();
//show the selected one
$("#"+submission).show();
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<select id="submissionType">
<option>Choose Submission Type</option>
<option value="member-submission">member-submission</option>
<option value="researcher-submission">researcher-submission</option>
<option value="student-submission">student-submission</option>
<option value="paper-submission">paper-submission</option>
</select>
<div class ="new-member-background">
<div class ="member-submission" id="member-submission">
<form action="SubmitData.php" method="post">
<input type="text" name="first" placeholder="First Name" />
<br/>
<input type="text" name="last" placeholder="Last Name" />
<br/>
<input type="text" name="title" placeholder="Title" />
<br/>
<input type="text" name="institution" placeholder="Institution" />
<br/>
<input type="number" name="dept_code" placeholder="Department Code" />
<br/>
<input type="text" name="division" placeholder="Division" />
<br />
<input type="text" name="email" placeholder="Email" />
<br/>
<input type="text" name="website" placeholder="Website" />
<br/>
<button type="submit" name="submit">Sign Up</button>
</form>
</div>
/**...Other divs...*/
</div>

Getting values with javascript

I started learning javascript a few weeks ago, the problem is that with my code I don't get the values that I put and I don't find where the problem could be.
function muestraDatos(){
var var1=document.getElementById("clogin").value;
var var2=document.getElementById("cpassword").value;
var var3=document.getElementById("cemail").value;
var var4=document.getElementById("cnombre").value;
var var5=document.getElementById("capellido").value;
var var6=document.getElementById("cfecha").value;
var var7=document.getElementById("cedad").value;
var var8=document.getElementById("ccolor").value;
var var9=document.getElementById("ccalle").value;
var var10=document.getElementById("ccpostal").value;
var var11=document.getElementById("cpoblacion").value;
var var12=document.getElementById("cprovincia").value;
var var13=document.getElementById("ctelefono").value;
var var14=document.getElementById("csemestre").value;
var var15=document.getElementById("ccarrera").value;
var var16=document.getElementByName('cinteres').value;
alert("Login: "+var1+"\nPassword: "+var2+"\nEmail: "+var3+"\Nombre: "+var4+" "+var5+"\nFecha de nacimiento: "+var6+"\nEdad: "+var7+"\nColor preferido: "+var8+"\nCalle: "+var9+"\nCódigo postal: "+var10+"\nPoblación: "+var11+"\nProvincia: "+var12+"\nTeléfono: "+var13+"\nSemestre: "+var14+"\nCarrera: "+var15+"\nInterés: "+var16);
}
<form onsubmit="return muestraDatos()">
<fieldset>
<legend>Solicitud socio</legend>
<label>Login: </label>
<input type="text" id="clogin" />
<br/>
<label>Password: </label>
<input type="text" id="cpassword" />
<br/>
<label>Email: </label>
<input type="email" id="cemail" />
<br/>
<strong>Datos personales:</strong>
<br/>
<label>Nombre: </label>
<input type="text" id="cnombre" />
<br/>
<label>Apellido: </label>
<input type="text" id="capellido" />
<br/>
<label>Fecha de nacimiento: </label>
<input type="date" id="cfecha" />
<br/>
<label>Edad: </label>
<input type="number" min="18" max="100" step="1" value="18" id="cedad" />
<br/>
<label>Color preferido: </label>
<input type="color" id="ccolor" />
</fieldset>
<fieldset>
<legend>Contacto</legend>
<label>Calle: </label>
<input type="text" id="ccalle" />
<br/>
<label>Código postal: </label>
<input type="text" id="ccpostal" />
<br/>
<label>Población: </label>
<input type="text" id="cpoblacion" />
<br/>
<label>Provincia: </label>
<input type="text" id="cprovincia" />
<br/>
<label>Teléfono: </label>
<input type="tel" id="ctelefono" />
<br/>
<strong>Datos estudiante:</strong>
<br/>
<label>Semestre </label>
<select id="csemestre">
<option value="semestreP">primero</option>
<option value="semestreS">segundo</option>
</select>
<label>Carrera </label>
<select id="ccarrera">
<option value="disenyo">diseño</option>
<option value="arquitectura">arquitectura</option>
<option value="derecho">derecho</option>
<option value="otra">otra</option>
</select>
<br /> Interés
<br/>
<label>Pintar</label>
<input type="radio" name="cinteres" value="pintar" />
<label>Hacer deporte</label>
<input type="radio" name="cinteres" value="hacerdeporte" />
<label>Ver peliculas</label>
<input type="radio" name="cinteres" value="verpeliculas" />
<label>Escuchar musica</label>
<input type="radio" name="cinteres" value="escucharmusica" />
<label>Leer</label>
<input type="radio" name="cinteres" value="leer" />
<br />
<input type="submit" value="Enviar datos" />
</fieldset>
</form>
See this fiddle
You had a typo here in this line
var var16 = document.getElementByName('cinteres').value;
It's actually
var var16 = document.getElementsByName('cinteres').value;
You missed an 's' in getElementsByName.
Also, according to the docs, document.getElementsByName
Returns a nodelist collection with a given name in the (X)HTML
document.
Thus, your code needs to be replaced as
var var16 = document.getElementsByName('cinteres')[index].value;
where index is the index position of the nodelist that is returned.

Javascript Document Window

Why wont my popup window pop up?
My user should enter information for an appointment. Once Submit is hit a document window should pop up. The submit button appears to work. The clear button is working also. I programmed a function to handle the window and set the onSubmit to return the function.
< script type = "text/javascript" >
function popUpWindow() { //window should return user's name in a window
newWin = window.open('', 'NewWin', 'toolbar=no,status=no,width=500,height=200');
newWin.document.write("<body bgcolor='yellow'><h3>Appointment Confirmation</h3>);
newWin.document.write("
Your name is: " + document["
form "].name.value);
newWin.document.close();
}
</script>
<html>
<head>
<title>Project</title>
</head>
//this form should accept user's input
<body>
<form name="form" onSubmit="return popUpWindow();">
Please enter your name:
<input type="text" name="name" value="" size="50" />
</p>
<p>
Address:
<input type="text" name="address" size="50" />
</p>
<p>
Phone:
<input type="text" name="area_code" size="10" />
</p>
<p>
Email:
<input type="text" name="email" value="" size="20" />
</p>
<p>
<legend>Stylist</legend>
</p>
<input type="radio" name="stylist" id="stylist1" value="dream" />Dream
<input type="radio" name="stylist" id="stylist2" value="aubrey" />Aubrey
<input type="radio" name="stylist" id="stylist3" value="stag" />Stag
<input type="radio" name="stylist" id="stylist1" value="halo" />Halo
<p>
<legend>Services</legend>
</p>
<input type="checkbox" name="service" id="service1" value="cut" />Cut
<br/>
<input type="checkbox" name="service" id="service2" value="relaxer" />Relaxer
<br/>
<input type="checkbox" name="service" id="service1" value="weave" />Weave
<br/>
<input type="checkbox" name="service" id="service1" value="braids" />Braids
<br/>
<input type="checkbox" name="service" id="service1" value="wash" />Wash and Style
<br/>
<input type="checkbox" name="service" id="service1" value="natural" />Natural
<br/>
<p>Leave Comments</p>
<textarea name="comments" id="comments" align="left" rows "8" cols "75"></textarea>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</form>
</body>
</html>

Calling a Object Oriented function from jQuery

I am kind of new to JQuery and Javascript and need your help on what I am missing here. I know the code works in jsfiddle.net but when I actually run it on my computer it's not doing anything. I want to keep the Object Oriented functions in "updated-formcheck.js" file separately.
I have a form validation HTML file with a jQuery function that calls my "updated-formcheck.js" file that checks all the empty fields and returns a msg. But when a submit button is clicked, nothing happens. Can you tell me why?
HTML file:
<script src="updated-formcheck.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<form id="myform" method="post" action="#">
<fieldset>
<label for="attendee">I am a...<font color="red">*</font>:<br />
<br />
</label>
<select id="attendee" name="attendee" >
<option value="">-- Please Choose --</option>
<option value="RETURNING" >Returning Attendee</option>
<option value="FIRST_TIME" >First Time Attendee</option>
</select>
<label for="fullName"><br />
<br />
Full Name<font color="red">*</font>:</label>
<p><input type="text" id="fullName" name="fullName" value="" />
</p>
<p> </p>
<label for="address1">Street Address<font color="red">*</font>:</label>
<p>
<input type="text" id="address1" name="address1" value=""/>
</p>
<p>
<input type="text" id="address2" name="address2" value="" />
</p>
<label for="city"><br />
City<font color="red">*</font>:</label>
<p>
<input type="text" id="city" name="city" value="" />
</p>
<label for="stateProvince"><br />
State/County/Province:</label>
<p>
<input type="text" id="stateProvince" name="stateProvince" value="" />
</p>
<label for="zipPostalCode">ZIP/Postal Code:<br />
</label>
<p>
<input type="text" id="zipPostalCode" name="zipPostalCode" value="" />
</p>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" id="btnSubmit"/>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click(function(e) {
validateNow(e);
});
});
</script>
In "updated-formcheck.js" file:
function validateNow(eventObj){
var isValid = true;
$('input[type="text"].required, textarea.required, select.required').each(function() {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red",
"background": "#FFCECE"
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if (isValid == false) {
eventObj.preventDefault();
alert(this.e);
}else
this.s;
}
Because
$('input[type="text"].required, textarea.required, select.required')
in your code currently return an empty array, so each function is not called.
This is because you are looking for dom elements with a css class "required" that you doesn't have.
To get your code working I added a "required" class, which your js code is looking for, on the city element. I also updated the jQuery bind event to the form submit instead of a button click.
<html>
<head>
</head>
<body>
<form id="myform" method="post" action="#">
<fieldset>
<label for="attendee">I am a...<font color="red">*</font>:<br />
<br />
</label>
<select id="attendee" name="attendee" >
<option value="">-- Please Choose --</option>
<option value="RETURNING" >Returning Attendee</option>
<option value="FIRST_TIME" >First Time Attendee</option>
</select>
<label for="fullName"><br />
<br />
Full Name<font color="red">*</font>:</label>
<p><input type="text" id="fullName" name="fullName" value="" />
</p>
<p> </p>
<label for="address1">Street Address<font color="red">*</font>:</label>
<p>
<input type="text" id="address1" name="address1" value=""/>
</p>
<p>
<input type="text" id="address2" name="address2" value="" />
</p>
<label for="city"><br />
City<font color="red">*</font>:</label>
<p>
<input type="text" id="city" name="city" value="" class="required" />
</p>
<label for="stateProvince"><br />
State/County/Province:</label>
<p>
<input type="text" id="stateProvince" name="stateProvince" value="" />
</p>
<label for="zipPostalCode">ZIP/Postal Code:<br />
</label>
<p>
<input type="text" id="zipPostalCode" name="zipPostalCode" value="" />
</p>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" id="btnSubmit"/>
</fieldset>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="updated-formcheck.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myform').on('submit', function(e) {
//e.preventDefault();
validateNow(e);
return false;
});
});
</script>
</body>
</html>

Categories