I want to change the label text based on the selection of the radio button. Could you please help me to do it easily. Here is my code.
<div class="control-group ">
<div class="controls">
<label class="radio inline">
<input type="radio" name="btype[]" id="private" value="private" checked>Private
</label>
<label class="radio inline">
<input type="radio" name="btype[]" id="business" value="business">Business Advertiser
</label>
</div>
</div>
This is the label that i want to change the text
<div class="control-group " >
<label class="control-label" id="labelName">Name</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" id="name" name="name" placeholder="">
</div>
</div>
</div>
<div class="control-group ">
<label class="control-label" id="labelNum">NIC</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" id="regNum" name="regNum" placeholder="">
</div>
</div>
</div>
This is my javascript
<script type="text/javascript">
$(document).ready(function()
{
if (($('input[name=btype]:radio:checked').val())=="business")
{
document.getElementById("labelName").innerHTML="Company Name";
document.getElementById("labelNum").innerHTML="Reg No.";
}
}
);
</script>
I rewrote the code for you in a better way. When you have jQuery use it to the best. Don't get messed up by handling JavaScript. jQuery is there to do it for you.
<script type="text/javascript">
$(document).ready(function()
{
if ($('#business').is(':checked'))
{
$('#labelName').text("Company Name");
$('#labelNum').text("Reg No.");
}
}
);
</script>
youre mixing jquery in with your js, so heres jquery
<script type="text/javascript">
$(document).ready(function(){
$('input[name=btype]:radio:checked').click(function(e){
if($(e.currentTarget).val()==='business') {
$("#labelName").text("Company Name");
$("#labelNum").text("Reg No.");
}
});
});
</script>
JsFiddle
onclick="document.getElementById('labelName').innerHTML='NEWLABELNAME'"
You can achieve this by adding a change listener to that inputs and getting the value of the selected one
I have added some HTML5 attributes to avoid getting more DOM
please look at data-text
<div class="control-group ">
<div class="controls">
<label class="radio inline">
<input type="radio" data-text="private" name="btype[]" id="private" value="private" checked>Private
</label>
<label class="radio inline">
<input type="radio" data-text="Business Advertiser" name="btype[]" id="business" value="business">Business Advertiser
</label>
</div>
</div>
Here is your JS and its jQuery
$(document).ready(function(){
$('input[name="btype[]"]').change(function(){
alert($(this).data('text'));
});
});
You can add more than data-* attributes like price or whatever you want and getting the value of it by using $(this).data('*');
It's used like this to make your HTML valid and I used it to avoid getting parent text
Check this fiddle http://jsfiddle.net/gK6bU/1/
I hope this can help :)
Related
I have a form and a checkbox. By click on the checkbox, a div within some other divs will show up or hide. This works! But, if i visit my page with an id like xxxxx.php?id=10, the checkbox is checked but the divs are hide. if i click on the checkbox, the divs will show up, but the checkbox is unchecked (bad for e.g. mysql updates).. hope anyone can help me by this issue..
Here my code:
$(document).ready(function() {
$('#Show').hide();
$("input[name=mycheckbox]").click(function () {
$('#Show').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<div class="form-group">
<div class="form-group">
<div class="checkbox-inline">
<label>
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="yes"> my option
</label>
</div>
</div>
</div>
<div id="Show">
<div class="form-group">
<label for="textinput" class="control-label">Company </label>
<div class="">
<input type="text" class="form-control" name="name" id="name" placeholder="" value="">
</div>
</div>
</div>
</form>
My input field have this code (php doesn't work in the snippet):
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="yes" <?php if (isset($_GET['id'])) {echo $row->mycheckbox == "yes" ? 'checked="checked"' : "";}?>
thanks for your help!
I would recommend to use change event, trigger using .trigger('change') on page load so that the div in sync with the state of checkbox element.
Also you should .toggle(display)
$("input[name=mycheckbox]").change(function () {
$('#Show').toggle(this.checked);
}).trigger('change');
When the user picks either phone or email I want the form to then generate a box to enter the details of which they selected. How do I do this? Thanks.
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" value="<?= (isset($fields['phone']) ? $fields['phone'] : '' )?>"/>
</div>
<div class="field-container full clearfix">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" value="<?= (isset($fields['email']) ? $fields['email'] : '' )?>"/>
</div>
Here's a snippet that shows you how to do that with javascript:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
Please note that I added a Id to the select element and to the input elements.
EDIT | USAGE
Create a file, call it script.js or whatever you like and put this in it:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
Save the file to a folder on your server that is accesible. For example /public/js/script.js
In your html, add
<script src="/public/js/script.js"></script> <!-- or however your path is -->
to the very end of your file, directly before the closing </body> tag So that it looks like this
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
<script src="/public/js/script.js"></script> <!-- here is the script included -->
</body>
That's it.
This worked for me:
Add an id to your select: select name="fields[contact]" id="contact"
Set phone and email fields to hidden by using a class or inline style: div class="field-container full clearfix hide-this" id="phone-container"
--or just set style: display:none;
Javascript:
$('#contact').change(function(){
if(this.selectedOptions[0].text == 'phone') {
$('#phone-container').show().focus();
}else{$('#phone-container').hide();}
});
This should do the trick... let me know?
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
.field-hide{
display: none;
}
</style>
<script>
function valChange(ele){
var fields = document.getElementById("container").children;
for(var i=0; i < fields.length; i++){
fields[i].classList.add("field-hide");
}
switch(ele.value){
case "phone":
document.getElementById("phone").classList.remove("field-hide");
break;
case "email":
document.getElementById("email").classList.remove("field-hide");
break;
}
}
</script>
</head>
<body>
<div class="field-container full clearfix">
<label class="required">What is your preferred method of contact?</label>
<select type="text" name="fields[contact]" onchange="valChange(this)">
<option value="blank" selected disabled>Choose</option>
<option value="phone">Quoted</option>
<option value="email">Labour Only</option>
</select>
</div>
<div id="container">
<div class="field-container full clearfix field-hide" id="phone">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" placeholder="enter phone number">
</div>
<div class="field-container full clearfix field-hide" id="email">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" placeholder="enter email">
</div>
</div>
</body>
</html>
I have the following form that needs to feed into the database but I would like it to be validated before it can be saved into the database :
<form name="add_walkin_patient_form" class="add_walkin_patient_form" id="add_walkin_patient_form" autocomplete="off" >
<div class="form-line">
<div class="control-group">
<label class="control-label">
Patient Name
</label>
<div class="controls">
<input type="text" name="patientname" id="patientname" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Patient Phone Number
</label>
<div class="controls">
<input type="text" name="patient_phone" id="patient_phone" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Department
</label>
<div class="controls">
<select name="department" required="" class="department" id="department">
<option value="">Please select : </option>
<option value="Pharmacy">Pharmacy</option>
<option value="Laboratory">Laboratory</option>
<option value="Nurse">Nurse</option>
</select>
</div>
</div>
</div>
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
</form>
And the submit is done by a jquery script using the following script :
<script type="text/javascript">
$(document).ready(function () {
//delegated submit handlers for the forms inside the table
$('#add_walkin_patient_button').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url() ?>index.php/reception/add_walkin', $('#add_walkin_patient_form').serialize(), function () {
//success do something
// $.notify("New Patient Added Succesfully", "success",{ position:"left" });
$(".add_walkin_patient_form").notify(
"New Walkin Patient Added Successfully",
"success",
{position: "center"}
);
setInterval(function () {
var url = "<?php echo base_url() ?>index.php/reception/";
$(location).attr('href', url);
}, 3000);
}).fail(function () {
//error do something
$(".add_walkin_patient_form").notify(
"There was an error please try again later or contact the system support desk for assistance",
"error",
{position: "center"}
);
})
})
});
</script>
How can I put form validation to check if input is empty before submitting it into the script?
I am using javascript to do the validations.
Following is the form code:
<form action="upload.php" method="post" onSubmit="return validateForm()">
<input type="text" id="username">
<input type="text" password="password">
<input type="submit" value='Login' name='login'>
</form>
To perform validation write a javascript function:
<script>
function checkform(){
var uname= document.getElementById("username").value.trim().toUpperCase();
if(uname=== '' || uname=== null) {
alert("Username is blank");
document.getElementById("username").backgroundColor = "#ff6666";
return false;
}else document.getElementById("username").backgroundColor = "white";
var pass= document.getElementById("password").value.trim().toUpperCase();
if(pass=== '' || pass=== null) {
alert("Password is blank");
document.getElementById("password").backgroundColor = "#ff6666";
return false;
}else document.getElementById("password").backgroundColor = "white";
return true;
}
</script>
You are using,
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
Here, submit button is used for submitting a form and will never trigger click event. Because, submit will be triggered first thus causing the click event skip.
$('#add_walkin_patient_button').on('click', function (e) {
This would have worked if you have used normal button instead of submit button
<input type="button">Submit</button>
Now to the problem. There are two solution for it ,
If you use click event, then you should manually trigger submit on correct validation case,
<input type="button" id="add_walkin_patient_button">Submit</button>
//JS :
$("#add_walkin_patient_button").click(function() {
if(valid){
$("#form-id").submit();
}
Another option is to use submit event;which is triggered just after you click submit button. Here you need to either allow form submit or halt it based on your validation criteria,
$("#form-id").submit(function(){
if(invalid){
//Suppress form submit
return false;
}else{
return true;
}
});
P.S
And i would recommend you to use jQuery Validate as suggested by #sherin-mathew
make a javascript validation method (say, validateForm(), with bool return type). add [onsubmit="return validateForm()"] attribute to your form and you are done.
You need to prevent default action.
$('#add_walkin_patient_form').on('submit', function(e) {
e.preventDefault();
//Validate form and submit
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#first{
display: none;
}
</style>
<div class="container"><br>
<div class="col-lg-6 m-auto d-block">
<form action="" method="" onsubmit="return validation()" class="bg-light">
<div class="form-group">
<label for="">Title</label>
<span class="text-danger">*</span>
<!-- <input class="form-control" type="text" > -->
<select name="title" id="title" class="form-control" >
<option value=""class="form-control" >Select</option>
<option value="Mr" class="form-control">Mr</option>
<option value="Mrs" class="form-control">Mrs</option>
</select>
<span id="tit" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="firstName">FirstName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="First name" id="firstName" >
<span id="first" class="text-danger font-weight-bold"> </span>
</div>
<div class="col">
<label for="lastName">LastName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Last name" id="lastName">
<span id="last" class="text-danger font-weight-bold"> </span>
</div>
</div>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Email" id="email">
<span id="fillemail" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="contact">Your Contact</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Contact Number" id="contact">
<span id="con" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="password">Your Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="password">
<span id="pass" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="conPassword">Confirm Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="conPassword">
<span id="conPass" class="text-danger font-weight-bold"> </span>
</div>
<div class="checkbox">
<label><input type="checkbox"> I accept Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve Email Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve SMS Terms and Conditions</label>
</div>
<input type="submit" name="submit" value="SignUp" id="signUp" class="btn btn-success" autocomplete="off">
</form><br><br>
</div>
</div>
<script type="text/javascript">
function validation(){
var title = document.getElementById('title').value;
var firstName = document.getElementById('firstName').value;
var email=document.getElementById('email').value;
var contact=document.getElementById('contact').value;
var password=document.getElementById('password').value;
var conPassword=document.getElementById('conPassword').value;
var signBut=document.getElementById('signUp');
console.log(firstName);
if(title == ""){
document.getElementById("tit").innerHTML =" Please select the title feild first field";
return false;
}
// if(firstName == "" & firstName.length<=3){
// document.getElementById("first").innerHTML =" Please Enter First Name";
// return false;
// document.getElementById("signUp").addEventListener("click", function(event){
// event.preventDefault()
// });
// }
signBut.addEventListener('click',function(e){
if(firstName=="" & firstName<3)
{
document.getElementById("first").innerHTML="Please Enter proper Name";
e.preventDefault();
}
},false);
if(lastName == ""){
document.getElementById("last").innerHTML =" Please Enter Last Name";
return false;
}
else if(email ==""){
document.getElementById("fillemail").innerHTML="Please Enter Email";
}
else if(contact ==""){
document.getElementById("con").innerHTML="Please Enter Your Contact";
}
else if(password ==""){
document.getElementById("pass").innerHTML="Please Enter Your Password";
}
else if(conPassword ==""){
document.getElementById("conPass").innerHTML="Please Confirm Password";
}
}
</script>
</body>
</html>
I think you should use type button
and then eventClick function of jquery
I develop an app using codigniter. In view, I have a form like this :
<div class="box-content">
<?php
$properties = array('class' => 'form-horizontal', 'id' => 'myForm');
echo form_open("control_request/userRequest", $properties);
?>
<fieldset>
<div class="control-group">
<label class="control-label">Jenis Request :</label>
<div class="controls" id="chekboxes">
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Login" value="Login" > Login </label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Printer" value="Printer"> Printer </label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Monitor" value="Monitor"> Monitor</label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Computer" value="Computer"> Computer</label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Network" value="Network"> Network</label>
<label class="checkbox inline"><input type="checkbox" name="request[]" id="Lain-lain" value="Lain-lain" > Lain-lain</label>
</div>
</div>
<div class="control-group hidden-phone">
<label class="control-label" for="Complaint" Complaint : </label>
<div class="controls">
<textarea class="cleditor" name="Complaint" id="Complaint" rows="3"></textarea>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit" >Submit</button>
<button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
Now, I create some javascript using jquery to validate, if the checkbox and textarea was qualify before submit. Here is the logic of jquery :
<script>
$(document).ready(function() {
$("#submit").click(function(e){
if (chekbox not selected at least one ) {
<p> Please choose at least one </p>
}
if textbox is empty {
<p> Pleaser fill the textbox </p>
}
if (all qualified)
submit
});
</script>
I just wanna check all of the element is qualified before submitting. But if not qualified, there will be a error message like this
()Checkbox1 ()Checkbox2 ()Checkbox3 ()Checkbox 4 <p>Please select one</p>
<textarea></textarea> <p>Please describe your complaint</p>
I am using jquery 1.9.1 , I will keep learn, and for the help thank you so much..
JSFIDDLE
Your question is not clear ..but it may help you what do you need
$("textarea:empty").length == 0 // text area empty
$(".checkbox [type=checkbox]:checked").length >= 1 // at least one is selected
If you need to make the textarea mandatory, use requierd
attribute. The jQuery validate plugin that you have used will do the
rest of the trick for validation.
For checking if at least one of the checkboxes is selected, you can
add one rule for checkboxes:
rules: {
'request[]': {
required: true,
minlength:2
}
},
OR
You can add a custom rule:
$.validator.addMethod("request[]", function(value, elem, param) {
if($(".request[]:checked").length > 0){
return true;
}else {
return false;
}
},"You must select at least one checkbox to continue");
I used all of the helpful answers on this site to try to build a jquery script to select radio buttons, but for some reason they don't work. Am I doing something wrong? For the sake of simplicity I've started back from square one.
I've attached the format that the php-generated form produces below. I tried multiple browsers, but was unable to get any button to select anything. Is there some complexity I'm not taking into account? The page is a .php page, and the form is generated in php.
Sorry for the basic question -- any help would be greatly appreciated. Not sure if it's relevant, but I want these buttons to work on mobile as well as various browsers.
Form Code:
<form class="form-horizontal" method="get" action="submit.php" name="form">
<div class="control-group">
<div class="row-fluid">
<div class="span2"></div>
<div class="span8">
<label class = "control-label" for="input1"> foreign policy </label>
<div class="controls">
<label class="checkbox inline"><input type="radio" name="group1" id="1_l" value="1_l"> Liberal</label>
<label class="checkbox inline"><input type="radio" name="group1" id="1_m" value="1_m"> Moderate</label>
<label class="checkbox inline"><input type="radio" name="group1" id="1_c" value="1_c"> Conservative</label>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span2"></div>
<div class="span8">
<br>
<center><button type="submit" class="btn btn-danger btn-large">Generate</button></center>
</div>
<div class="span2"></div>
</div>
</form>
Jquery Code:
$('button').click(
function() {
$('#1_l').attr('checked', true);
}
);
Make sure to only bind the handler after the DOM has been loaded:
$(function() {
$('button').click(function() {
$('#1_l').attr('checked', true);
});
});
Use the ":checked" selector in jQuery to select the checked input, otherwise you only get the first one.
$(function () {
$('button.btn').click(function () {
var $box = $('.checkbox input:checked');
if ($box.length > 0)
alert($box.val());
});
});
Here is what i see you have a div that was not closed i closed it
I changes the button type to button rather than submit so i could see it work and all was good
See my working DEMO
<form class="form-horizontal" method="get" action="submit.php" name="form">
<div class="control-group">
<div class="row-fluid">
<div class="span2"></div>
<div class="span8">
<label class = "control-label" for="input1"> foreign policy </label>
<div class="controls">
<label class="checkbox inline"><input type="radio" name="group1" id="1_l" value="1_l"> Liberal</label>
<label class="checkbox inline"><input type="radio" name="group1" id="1_m" value="1_m"> Moderate</label>
<label class="checkbox inline"><input type="radio" name="group1" id="1_c" value="1_c"> Conservative</label>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span2"></div>
<div class="span8">
<br>
<center><button type="button" class="btn btn-danger btn-large">Generate</button></center>
</div>
<div class="span2"></div>
</div>
</div>
</form>
and here is the jQuery
$(function () {
$('button').click(function() {
$('#1_l').attr('checked', true);
});
}