I am new to javascript and I am trying to add a conditional field to a form. I have looked at these posts:
How do you create a hidden div that doesn't create a line break or horizontal space??
conditional display of html element forms
I have come up with this little example so far which works fine.
<html>
<head>
<script language="javascript">
function cucu(form){
if(form.check.checked){
document.getElementById("cucu").style.visibility="visible";
}
else{
document.getElementById("cucu").style.visibility="hidden";
}
}
function load()
{
document.getElementById("cucu").style.visibility="hidden";
}
</script>
</head>
<body onload="load()">
<form id="form">
<input type="checkbox" name="check" onclick="cucu(this.form)" >
<div id="cucu">
CUCU
</div>
</form>
</body>
<html>
I have tried the same method on a larger side and the only change is that the hidden element is a text field but it just doesnt' work.
This is the part of the form:
Album: <INPUT TYPE="checkbox" NAME="checkAlbum" onclick="checkAlbum(this.form)" id="idAlbum">
<div id="divAlbum" >
Choisir un album : <input type="text" name="Album" list="Albums">
<datalist id="Albums">
<?php
$requete = 'SELECT DISTINCT titreAlbum FROM Album';
$resultat = mysqli_query($connexion, $requete);
while($row = mysqli_fetch_assoc($resultat)){
echo '<option value="'.$row['titreAlbum'].'">';
}
?>
</datalist> <br><br>
</div>
My head looks as follows:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html ; charset=UTF-8" />
<title>BLABLA</title>
<link rel="stylesheet" type="text/css" href="include/styles.css">
<script language="javascript" >
function hideElements(){
document.getElementById("divAlbum").style.visibility="hidden";
}
function checkAlbum(form){
if(form.checkAlbum.checked){
document.getElementById("divAlbum").style.visibility="visible";
}else{
document.getElementById("divAlbum").style.visibility="hidden";
}
}
</script>
</head>
I really don't know what the problem is. I've checked the functions again and again. Any suggestions for the possible error? Thanks
The reason your button is not working is that this refers to the clicked input itself. The form property on the input refers to the value of the form attribute, not the actual form. In reality you don't need the form attribute, you can simply use this.checked to see if the corresponding input is currently checked.
Album: <INPUT TYPE="checkbox" NAME="checkAlbum" onclick="checkAlbum(this)" id="idAlbum">
function checkAlbum(cb){
if(cb.checked){
document.getElementById("divAlbum").style.visibility="visible";
}else{
document.getElementById("divAlbum").style.visibility="hidden";
}
}
Beyond this I would suggest that you consider not applying your JavaScript inline. Keeping your code separate from your mark up improves readability and can help prevent errors. You might consider using the jQuery framework as it will make this sort of thing much easier.
$(function(){
$('#idAlbum').on('change', function() {
// use change instead of click in case there's a label involved
$('#divAlbum').toggle(this.checked);
});
});
Related
Error:
TypeError: d.options is undefined while(i<=d.options.length){
Hi i have this javascript of mine which has the select option to choose from. and from choosing from the select options it will display to the textbox field im using this onchange and using it while loop. can someone help me how to figure this out?? using while loop code?
Here's my code below
<!DOCTYPE html>
<html>
<head>
<title>Activity 2 while loop</title>
<script type="text/javascript">
function tellMe(d){
var i = 0;
while(i<=d.options.length){
if(d.listbox1.options[i].selected == true){
d.choose.value = d.listbox1.options[i].text;
}
}
}
</script>
</head>
<body>
<form name="form1">
<p>Girl's qualities you want?</p>
<select name="listbox1" size="5" onchange="tellMe(this.form)">
<option>Pretty</option>
<option>Sexy</option>
<option>Hot</option>
<option>Intelligent</option>
<option>Funny</option>
</select>
<br />
<p>
You Choose: <input type="text" name="choose" />
</p>
</form>
</body>
</html>
any help is muchly appreciated! thanks
Fiddle
Fixed it:
<!DOCTYPE html>
<html>
<head>
<title>Activity 2 while loop</title>
<script type="text/javascript">
function tellMe(d){
document.getElementById("choose").value = d.value;
}
</script>
</head>
<body>
<form name="form1">
<p>Girl's qualities you want?</p>
<select name="listbox1" size="5" onchange="tellMe(this)">
<option>Pretty</option>
<option>Sexy</option>
<option>Hot</option>
<option>Intelligent</option>
<option>Funny</option>
</select>
<br />
<p>
You Choose: <input type="text" id="choose" name="choose" />
</p>
</form>
</body>
</html>
You were trying to get this.form but it should have been this, then the value of this (this.value).
Then, all you had to do was set the input type with name='choose', however I gave it an ID of choose to make it easier to select, then gave that value d.value, which was the value of listbox1.
You are passing the form element, which doesn't have options. Change d.options to d.listbox1.options
while(i<=d.listbox1.options.length){
After that is fixed your second problem will become apparant, whch is that you fail to increment i:
while(i<=d.listbox1.options.length){
...
i++;
}
You aren't incrementing i. You need to add i++ at the end of your while loop. You also need to target listbox1 in your while loop.
function tellMe(d){
var i = 0;
while(i<=d.listbox1.options.length){ // <-- use d.listbox1.options.length
if(d.listbox1.options[i].selected == true){
d.choose.value = d.listbox1.options[i].text;
}
i++; // <-- add increment here
}
}
I am creating a team registration form. and the required condition is that user must be already registered and can choose only registered members in the team.
for checking user existence in database i am using email.
The form contains multiple email fields triggered by a button that adds a field in the form
I need to check for all user's existence when user types in the respective email field using ajax call and display the result in <span class='form_hint'></span>
The form is contained in a hidden div and is called by colorbox
but it doesn't seem to work somehow
Here's my html code:
Update: Now Working fine
<!DOCTYPE html>
<html dir="ltr" lang="en-US"> <head>
<title>Event Description </title>
<meta charset="UTF-8"/>
<!--Colorbox-->
<link rel="stylesheet" media="screen" href="colorbox/css/styles.css" >
<link rel="stylesheet" media="screen" href="colorbox/css/colorbox.css" >
<script src="colorbox/js/jquery.min.js"></script>
<script src="colorbox/js/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
$(".register").colorbox({inline:true,maxHeight:"95%", maxWidth:"90%"} );
});
</script>
<!--Colorbox ends-->
</head>
<body>
<a class="register" href="#register">Event Registeration</a>
<script type="text/javascript">
function usercheck(){
$(document).ready(function(){
$('input[type="email"]').keyup(function() {
var name = $(this).val();
if(name=="")
{
$(".form_hint").html("");
}
else
{
$.ajax({
type: "POST",
url: "user_check.php",
data: { email: name } ,
success: function(html){
$(".form_hint").html(html);
}
});
return false;
}
});
});
}
</script>
<div style='display:none'>
<div id='register' style='padding:10px; background:#fff;'>
<center>
<form class="contact_form" action="../../register/register.php" method="post" name="contact_form">
<ul>
<li>
<h2>Registration</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" placeholder="mail#example.com" onkeyup="usercheck();" required />
<span class="form_hint">Proper format "mail#example.com"</span>
</li>
<span id="dynamicInput"></span>
<li><input type="button" value="+" onClick="addInput('dynamicInput');"/></li>
<li>
<button class="submit" type="submit">Register</button></h4>
</li>
</ul>
</form></center>
</div>
</div>
<script type="text/javascript">
function addInput(liName){
//var counter=1;
var newfield = document.createElement('li');
newfield.innerHTML = "<label for='email'>Email:</label><input type='email' name='email[]' onkeyup="usercheck();" placeholder='mail#example.com' /><span class='form_hint'></span>";
document.getElementById(liName).appendChild(newfield);
}
</script>
</body>
</html>
PHP code to check users in Database:
<?php
include('connect.php');
if(isset($_POST['email']))
{
$name=$_POST['email'];
$query=mysql_query("select * from user_details where email='$name'");
$row=mysql_num_rows($query);
if($row==1)
{
echo "Okay Pal!";
}
else
{
echo "User doesn't exist";
}
}
?>
I don't know where the error is as i am implementing it using dynamic fields for very first time
Also i want to know a good method to handle multiple email fields like i am using above.
I dont think your IF-Statement in your PHP-Code is executed.
You're checking for an email-parameter, but your ajax-data looks like data: "name="+ name
Try to change it to data: { email: name },
First of all selector $('#email[]') is invalid. Try adding some class to the email input or use this selector $('input[type="email"]') to add event handler to all email fields.
Next thing is keyup handler. Inside handler function you can use $(this) instead trying to select field again.
The last one consider using JSON as the data exchange type. On the server return string like: {registered:true} and on the client parse it as a JSON in the jQuery.ajax function setting dataType to JSON.
The Above code is now fully functional.
Earlier only 1st field was calling the function and checking through php. so as to resolve it, I added a
function usercheck(){}
to handle the user interactions.
And on every key up on <input type='email'> I added onkeyup() function that triggers usercheck() as:
<input type='email' name='email[]' onKeyUp='usercheck();'>
and result of the query is displayed within <span> with every <input type='email'> field
Thank you everyone for your valuable responses :) You made my day!
I'm trying to write a web page with various options that can be enabled/disabled.
However, it seems that those options are always enabled, regardless of whether the relevant check boxes are selected or not.
Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
function check() {
var options = "";
if (document.form1.nocase.value) {
options = "1";
}
if (document.form1.ck2.value) {
options = options + "2";
}
alert (options);
}
</script>
<form name="form1">
<input type="checkbox" name="nocase">option 1
<input type="checkbox" name="ck2">option 2
<input type="button" value="Check" onclick="check();">
</form>
<div id="results"></div>
</body>
</html>
I really am having problems understanding where the fault lies. Can anyone point it out?
Thanks in advance.
You should use the checked property and not the value property of your input fields:
if (document.form1.nocase.checked) {
//code here
}
The value attribute is string value that is sent to the server for every checked checkbox and you can specify its value in the html tag:
<input type="checkbox" name="nocase" value="nocase">
The checked property gives you the desired boolean that shows whether or not the checkbox is checked.
I´ve read a lot of post about jQuery serialize() but I cant get it to work with my form!
I works when I print out the form using html+php but not when I use javascript to print out the form. What am I missing?
I know there is a bunch of post about this but every one I´ve found is about ppl forgetting name="" or disabled the ( Try my code here: http://jsfiddle.net/ZBxkz/1/ )
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>MerBeer</title>
<!-- //jquery -->
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<!-- //Ajaxscript: -->
<script type="text/javascript">
$(document).ready(function () {
$("#knappen")
.delegate('button[name="minKnapp"]', "click", beer_insert);
$("#theForm")
.delegate('button[name="beer_form_submit"]', "click", serial);
function serial(){
var f = $('#beer_form'); // CHANGE THIS VALUE TO CHANGE FORM!! #beer_form and #testForm
var beerContainer = f.serialize();
alert (beerContainer);
}
function beer_insert() {
//hide first button
$('#dold').hide();
//Dynamically added form
$('#theForm').html('Test :<br><form name="beer_form" id="beer_form"><table id="beers">');
for (var i = 0; i < 1; i++){
$('#theForm').append('<tr><td><input type="text" name="beerCountry" id="beerNo_'+i+'_country" /></td></tr>');
}
$('#theForm').append('</table></form><br>');
$('#theForm').append('<button name="beer_form_submit">Second button</button><br>')
}
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- Form that works-->
<form id="testForm" name="testForm">
<table>
<?php
for($i = 0; $i < 3; $i++){
echo('<tr><td><input type="text" name="test" id="inget'.$i.'"/></td></tr>');
}
?>
<tr><td><input type="text" name="test" id="ingetA"/></td></tr>
<tr><td><input type="text" name="test" id="ingetB"/></td></tr>
</table>
</form>
<div id="theForm"></div>
<div id="knappen"><button id="dold" name="minKnapp">The Button</button></div>
</body>
I hope I got your question right, but probably you want this?: http://jsfiddle.net/jyM5Z/
Don't put your html together with many appends. Instead first build a complete html string and then add it to your container. This will not only make it much faster but will also protect you from unexpected behaviour because the browser parses your HTML fragment and changes it in order to make sense (like automatically close open tags).
You're not appending into your form, but rather you're appending after it. So when you call serialize, there's literally nothing to serialize.
// this creates the form
$('#theForm').html('Test :<br><form name="beer_form" id="beer_form"><table id="beers">');
// but these don't append INTO it
for (var i = 0; i < 1; i++){
$('#theForm')
.append('<tr><td><input type="text" name="beerCountry" id="beerNo_'+i+'_country" /></td></tr>');
}
$('#theForm').append('<button name="beer_form_submit">Second button</button><br>')
This is pretty much what you want your workflow to be:
// create my form
var my_dynamic_form = $('<form></form>');
// append to it
for (;;) {
my_dynamic_form.append('<input/>');
}
// append your form to the DOM
$('#my_form').append(my_dynamic_form);
I have a problem. I want the text to be filled by the default value when user lefts it blank here is my code. Please help me to tackle this error.
<html>
<head>
<title>
</title>
<script lang='javascript'>
function makeBlank(obj,defMsg){
if(obj.value==defMsg){
obj.value="";
}
}
function fillDefValue(obj,defMsg){
if(obj.value==""){
obj.value=defMsg;
}
}
</script>
</head>
<body>
<input style="width:190px" onblur="fillDefValue(this,'User Name')" onfocus="makeBlank(this,'User Name')" value="Name" name="fromname" id="fromname" type="text">
</body>
</html>
You don't have to pass the default value to the functions, it's integral part of the textbox element itself:
function makeBlank(obj) {
if(obj.value === obj.defaultValue){
obj.value = "";
}
}
function fillDefValue(obj) {
if(obj.value == "") {
obj.value = obj.defaultValue;
}
}
Then pass only the element:
onblur="fillDefValue(this);" onfocus="makeBlank(this);"
Live test case - it works on all major browsers, probably all browsers.
Your code has a minor error. The functions which make the text field blank or filled with default value have an if statement which checks the condition if(obj.value==defMsg) which is defMsg='User Name'. But in the text field you are assigning value = "Name" so the if condition never become true. Thats why your code is not working. You should either use <input .... value="User Name" ......> or you can call the both functions as <input ...onblur="fillDefValue(this,'Name')" onfocus="makeBlank(this,'Name')" vlaue="Name"....>. Doing any of these two changes the code will work fine. Here is your code with the first change I mentioned:
<html>
<head>
<title>
</title>
<script lang='javascript'>
function makeBlank(obj,defMsg){
if(obj.value==defMsg){
obj.value="";
}
}
function fillDefValue(obj,defMsg){
if(obj.value==""){
obj.value=defMsg;
}
}
</script>
</head>
<body>
<input style="width:190px" onblur="fillDefValue(this,'User Name')" onfocus="makeBlank(this,'User Name')" value="User Name" name="fromname" id="fromname" type="text">
</body>
</html>
You’re probably looking for the placeholder HTML attribute.
<input placeholder="e.g. username42">
You only need JavaScript as a fallback for older browsers. This jQuery plugin will take care of it for you. Here’s a demo: http://mathiasbynens.be/demo/placeholder