Im having trouble getting values from the checked radio:
<form id="addform" /*action="catch.php" method="POST"*/>
<div class="form-group input-container">
<label class="col-sm-7"> *Href looks like "/vacacy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="0" type="radio" required>
<label class="col-sm-7"> *Href looks like "https://www.test.com/vacancy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="1" type="radio" required>
</div>
</form>
This is the JavaScript code:
$( "#check" ).click(function()
{
var $inputs = $('#addform :input');
var values = {};
$inputs.each(function()
{
if (this.name === "vacancy_full_URL")
{
if (/* check if radiobutton is checked */)
{
values[this.name] = $(this).val();
}
}
else
{
values[this.name] = $(this).val();
}
});
});
I'm having trouble finding the right functions to check this with. My earlier attempt if (this.checked() === true) did not work. Can you please help me?
Use is(":checked") to find if a radio button is checked. Also there are few mistakes in html form like a you have make the form self closing. Secondly there was no item with id check
$("#check").click(function(e) {
e.preventDefault()
var $inputs = $('#addform :input');
var values = {};
$inputs.each(function() {
if (this.name === "vacancy_full_URL" && $(this).is(":checked")) {
values[this.name] = $(this).val();
} else {
values[this.name] = $(this).val();
}
});
console.log(values)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addform" action="catch.php" method="POST">
<div class="form-group input-container">
<label class="col-sm-7"> *Href looks like "/vacacy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="0" type="radio" required>
<label class="col-sm-7"> *Href looks like "https://www.test.com/vacancy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="1" type="radio" required>
</div>
<button type='submit' id='check'>Click</button>
</form>
You can handle click event on button and check radion click name with :checked
$(document).ready(function(){
$("#check").click(function(){
var radioValue = $("input[name='vacancy_full_URL']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
Please try this.
$(document).ready(function () {
$("#check").click(function () {
var values = {};
var other_data = $('input[type=radio]', $('#addform'));;
$.each(other_data, function (key, input) {
if (input.checked) {
values[input.name + "_checked"] = input.value;
} else {
values[input.name+ "_unchecked"] = input.value;
}
});
});
})
Related
In short, if a user selects yes to a radio option, I'm trying to obtain the data-name attribute from that input and push it to an array called accepted_array.
If a user selects no, then store data-name to declined_array.
Here is a visual to the markup:
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
Here are 2 approaches I've experimented with:
First approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var checkedVal = $this.val();
var accepted_array = [];
var declined_array = [];
if( checkedVal == "yes" ) {
var name = $this.data("name");
accepted_array.push(name);
} else {
declined_array.push(name);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + accepted_array.join(","));
});
});
}) (jQuery);
This only executes for the selected user and adds the name to both arrays.
Second approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var data = [];
var checked = $this.is(':checked');
var name = $this.attr('data-name');
if (checked) {
if (!data[name]) {
data[name] = []
}
data[name].push($this.val())
}
console.log(data);
});
});
}) (jQuery);
Which only adds the user to a single array.
If both select yes, I need both names in the accepted_array. If someone selects yes initially and then selects no I need to remove them from the accepted_array and vice versa.
You can use splice with inArray to remove value from array if someone selects yes initially and then selects no and vice versa.
Example:
var accepted_array = [];
var declined_array = [];
$('.guest__options-group > input[type=radio]').on('change', function() {
var $this = $(this);
var name = $this.data("name");
var checkedVal = $this.val();
var name = $this.data("name");
if (checkedVal == "yes") {
accepted_array.push(name);
declined_array.splice($.inArray(name, declined_array), 1);
} else {
declined_array.push(name);
accepted_array.splice($.inArray(name, accepted_array), 1);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + declined_array.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- options for John -->
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
I want to remove the disabled attribute from the button when each field is filled out.
My code works when a single input is filled.
What am i doing wrong here?
Here are the HTML and JS
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
if (e.value !== '') {
disabled = false
} else {
disabled = true
return false
}
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Continue</button>
It does not work because you want to have all inputs affect the state of a button, yet you only check one variable for adding/removing disabled property.
Here is a working code snippet with an example where i created an array of properties, one for each input, that i can refer to in every fired key up event
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
const disabled = Array(input.length).fill(true);
input.forEach(function (e, index) {
e.addEventListener('input', function () {
disabled[index] = e.value === ''; // simplified if/else statement of yours
if(disabled.some(Boolean)) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Prosegui</button>
Additionaly stoping the function execution when assigning disabled = true in the first else statement is also a wrong approach, as you most likely want to not only assign the disable value, but also the disabled property of the button.
EDIT: as mentioned in the comment by CID it is reasonable to change the event listener to input so we can handle the copying and pasting events as well
You are adding a keyup event for each input field.
that event only checks the current input field if it is empty or not.
it does not check the 3 input fields itself
this should do the trick:
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
const emptyFields = Array.from(input).filter( input => input.value === "");
disabled = emptyFields.length > 0;
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
You are enabling the submit button on keyup event of any 3 inputs. So it gets enabled on any 3 inputs.
Remove the return on disabled flow to disable button after clearing.
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
if (e.value !== '') {
disabled = false
} else {
disabled = true
// return false <-- this makes function exit before your disable button
}
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Continue</button>
Another solution is to check if all inputs are filled out on every change in any input.
addHandlers();
// Return true if all fields are not empty
function areAllFieldsFilledOut() {
let inputs = document.querySelectorAll('.form-control');
let result = true;
inputs.forEach(e => {
if (e.value === "")
result = false;
});
return result;
}
// Add keyup event handlers to all input fields
function addHandlers() {
let inputs = document.querySelectorAll('.form-control');
const button = document.querySelector('.submit-btn');
inputs.forEach(e => {
// On each change in any input, check if all inputs are
// not empty, and if true, enable the button
e.addEventListener('keyup', e => {
let result = areAllFieldsFilledOut();
if (result) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', 'disabled');
}
});
});
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Prosegui</button>
Here is my answer:
function checkInput() {
document.querySelectorAll('input').forEach(input => {
input.addEventListener('keyup', function () {
let emptyFieldsCount = Array.from(input).filter(input => input.value == "").length;
if (emptyFieldsCount > 0) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
});
}
Disabling jquery submit button until all the form inputs is filled.
Am working with Jquery and I have been trying to implement disabling form submission button until the whole form inputs are filled. i have tried most solution found here but it does not solve the issue. Thanks
$('.postbtn_video').click(function() {
var element = $(this);
var ID = element.attr('id');
var msg = $('#status').val();
var title = $('#title').val();
var video = $('#video').val();
var stat = $('#stat').val();
if (title == "") {
alert('Please Enter video Post Title?');
} else if (msg == "") {
alert('Please Enter Video Post Description');
} else if (video == "") {
alert('Enter Youtube Video Link');
} else if (stat == "") {
alert('Select Status');
} else {
var postData = "post=" + msg + "&title=" + title + "&video=" + video + "&stat=" + stat;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "posts.php",
data: postData,
cache: false,
success: function(html) {
$("ul#updatepost").prepend(html);
$("ul#updatepost li:first").slideDown("slow");
$('#status').val('');
$('#loader').hide();
}
});
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?">
</textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
</form>
Firstly apply disabled="disabled" to the button:
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
Secondly, you need a function which will check each field is empty or not!
Check below code:
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if(!empty){ // this will only check next inputs if empty is false, but once its set to true no further check will be made
if ($(this).val() == '') {
empty = true;
}
}
});
if (empty) {
$('.postbtn_video').attr('disabled', 'disabled');
} else {
$('.postbtn_video').removeAttr('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?"></textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
</form>
Maybe this will help. you can manipulated the Form Disabled attribute:
var checkboxes = document.getElementsByTagName('input');
//check all check all input elements to see if they are check-boxes
for (var i = 0; i < checkboxes.length; i++) {
//If the input is a check-box run script else skip over
if (checkboxes[i].type == 'checkbox') {
//If it is a check-box ensure the box is unchecked
checkboxes[i].checked = false;
}
}
$(document).ready(function()
{
//define Element by ID and create variable
var $checked = $('#field_human');
//define default state for attribute before handler function trigger
$("#submit").attr("disabled", !$checked.checked)
//On element handler trigger define function to execute each time handler is triggered
$checked.click(function()
{
//State to define instance on method
if ($checked.prop('checked'))
{
//return true
//remove element attribute state 'disabled'
$('#submit').removeAttr('disabled');
}
if($('#contactForm input').val() != '')
{
$('#submit').removeAttr('disabled');
}
else {
//return false
//set element attribute state 'disabled'
$("#submit").attr("disabled", !$checked.checked);
}
//return to ready-state to wait for handler to trigger again
return;
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<form class="form-horizontal" role="form" method="post" action="" id="contactForm" name="contactForm">
<div class="form-group">
<label for="inputblk" class="col-sm-3 control-label">Input Block</label>
<div class="col-sm-9">
<input name="inputblk" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-3 control-label">Are You <strong><u>Human</u>?</strong></label>
<div class="col-sm-9">
<input id="field_human" class="field_human" type="checkbox" name="human" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button id="submit" name="submit" type="submit" class="btn btn-dark btn-block btn-lg">Send</button>
</div>
</div>
</form>
1st:
inputs that you think are required, make it required! like below:
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link" required >
2nd:
Make your selection based on this attribute and check if values of these inputs are not empty. Disable the submit button if so.
3rd:
Make event listener to all inputs that have required attribute to listen user inputs.
something like this:
var l = $("[required='']");
function enableSubmit(l) {
if (l.length == 0) {
$("[name=post]").removeAttr('disabled');
} else {
for (var m = 0; m < l.length; m++) {
if (l[m].value.length == 0) {
$("[name=post]").attr("disabled", "disabled");
return;
}
}
$("[name=post]").removeAttr('disabled');
}
}
for (var m = 0; m < l.length; m++) {
l[m].addEventListener('input', function () {
enableSubmit(l);
});
}
First of all you need to add a disabled property to you input button by default like:
<input disabled name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
then in your jquery you need fire up a validate function that will check for all the inputs and if they are not empty you can simply remove the disabled property from your input button like:
$(document).on('keyup', "input:not([type='submit']", function () {
//set it to true by default
var valid = true;
//getting all the inputs except input submit
var inputTextboxes = $("input:not([type='submit'])");
inputTextboxes.each(function(e) {
//it enters this only if the valid is true for any one value, if valid is set to false at any point it won't check it for next inputs - works for first time
if (valid != false){
if ($(this).val()) {
valid = true;
}else{
valid = false;
}
}
else{
break; //breaks the loop
}
});
if (valid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Hope this helps
I have an issue, with ajax request. When button enter is clecked it is doubles ajax request. I spent 4 hours dealing with it and no effect at all. Can someone help me with it. I have created consol.log here. For better understanding of my bad code. Thank you in advanced!
let formSubmitHandler = (data) => {
console.log(data)
// $.ajax({ url: 'index.php',
}
let handleInputEdit = (data) => {
let onFocusHandler = (element) => {
element.keypress(function( event ) {
if ( event.which == 13) {
let inputData = element.val();
let name = element.attr('name');
return onHandlerFormData(name, inputData);
}
})
}
let onHandlerFormData = (name, data) => {
let str = `${name}=${data}`;
$('#data').html(str)
return formSubmitHandler(str);
}
let onEditHandler = () => {
let checkboxes = document.querySelectorAll('input[type=checkbox]');
for (let i = 0; i < checkboxes.length; i++) {
const element = checkboxes[i];
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", true);
if (element.checked) {
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", false)
.focus(function(){
onFocusHandler($(this));
})
}
}
};
onEditHandler();
$("input[type=checkbox]").on("click", onEditHandler);
}
handleInputEdit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainForm">
<label for="companyName">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="companyName"
type="text"
class="form-control"
aria-label="..."
name="companyName"
>
</div>
<label for="edrpou">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="edrpou"
type="text"
class="form-control"
aria-label="..."
name="edrpou"
>
</div>
</form>
You are calling onFocusHandler multiple times. You binding the onFocusHandler multiple times each time the checkbox is clicked. Moving the onFocusHandler from the definition of onEditHandler will solve this issue. Try out the following code,
The onEditHandler will change as follows,
let onEditHandler = () => {
let checkboxes = document.querySelectorAll('input[type=checkbox]');
for (let i = 0; i < checkboxes.length; i++) {
const element = checkboxes[i];
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", true);
if (element.checked) {
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", false)
}
}
};
And bind the onFocusHandler function with the checkboxes only once as follows,
$('input[type=checkbox]').each(function () {
onFocusHandler($(this).parent().next());
});
I have re-written the javascript to handle enabling/disabling the textboxes, and also to handle keyup event for the ENTER press.
I think the code is more readable this way, plus: it works as expected.
// disable all textboxes by default
$('input[type=text]').attr('disabled','disabled');
//only enable the textbox next to the checkbox if it was checked
$(document).on('click','input[type=checkbox]',function(){
if ($(this).is(':checked')) {
$(this).parent().siblings('input[type=text]')
.removeAttr('disabled');
} else {
$(this).parent().siblings('input[type=text]')
.attr('disabled','disabled');
}
});
//whenever the ENTER key is pressed within an enabled textbox, handle it
$(document).on('keyup','input[type=text]',function(e) {
if(e.which == 13) {
console.log( $(this).attr('id') + '=' + $(this).val() );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainForm">
<label for="companyName">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="companyName"
type="text"
class="form-control"
aria-label="..."
name="companyName"
>
</div>
<label for="edrpou">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="edrpou"
type="text"
class="form-control"
aria-label="..."
name="edrpou"
>
</div>
</form>
Like Ahmad... I also re-written your way too complex code.
It made my brain bleed.
And it does a so simple task in the end!
About changes on HTML, I only added the disabled attribute straith in the markup.
Have a look:
$("#mainForm input[type='checkbox']").on("click",function(){
var text_input = $(this).parent().next("input");
var text_input_dasbled = text_input.prop("disabled");
text_input.attr("disabled", !text_input_dasbled); // Toggle disabled
});
$("#mainForm input[type='text']").on("keyup",function(e){
if(e.which==13){
var data = {[$(this).attr("name")]:$(this).val()};
console.log(data)
// $.ajax({ ... });
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<form id="mainForm">
<label for="companyName">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="companyName"
type="text"
class="form-control"
aria-label="..."
name="companyName"
disabled>
</div>
<label for="edrpou">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="edrpou"
type="text"
class="form-control"
aria-label="..."
name="edrpou"
disabled>
</div>
</form>
I have created a stand alone code for enabling/disabling input field and it is working perfectly .
HTML:
Identification Type:
<select name="Identification-Type" id="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="23434">--sfgdg--</option>
<option value="135111">--dfgb--</option>
<option value="1165611">--gdg--</option>
<option value="114511">--vcbc--</option>
</select>
<!-- <input type="checkbox" class="Identification-Number" value="Identification-Number"
name="Identification-number" id="Identification-Number"> -->
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number" id="Identification-Number">
JS:
$('select[name="Identification-Type"]').change(function () {
var $this = $('#Identification-Number');
$this.attr("disabled", false);
$this.attr("disabled", ($(this).val() == '1111') ? true : false);
}).trigger('change');
JSFIDDLE LINK
But,when I tried to incorporate this logic in another form, it is not working .
HTML:
<form name="pancettaForm" method="post" action="demor" id="pancettaForm">
<ul>
<li>
<label for="PartyChoose">Choose Appropriate Party:</label>
</li>
<br>
<input id="person" name="PartyChoose" type="radio" value="update-person" class="required" />Person
<br />
<input id="organization" name="PartyChoose" type="radio" value="update-organization" class="required" />Organization
<br />
<li id="Family-Name" style="display: none;">
<input type="checkbox" class="Family-Name" value="Family-name" name="Family-name">
<label for="Family-Name"><em>*</em>Family Name:</label>
<input type="text" name="Family-Name" class="required">
</li>
<li id="Organization-Name" style="display: none;">
<inpname="Organization-name">
<label for="Organization-Name"><em>*</em>Organization Name:</label>
<input type="text" name="Organization-Name" class="required">
</li>
<div class="extraPersonTemplate">
<div class="controls-row">
<li id="Identification-Type" style="display: none;">Identification Type:
<select name="Identification-Type" class="Identification-Type">
<label for="Identification-Type">Identification Type:</label>
<option value="1111">--Select--</option>
<option value="1">--sdsd--</option>
<option value="2">--cxc--</option>
<option value="3">--cvcv--</option>
<select> <a id="Identification-Number" style="display: none;">
<input type="hidden" class="Identification-Number">
<label for="Identification-Number"><em>*</em>Identification Number:</label>
<input type="text" name="Identification-Number">
</a>
</li>
</div>
</div>
<div id="container"></div>
<a href="#" id="addRow" style="display: none;"><i class="icon-plus-sign icon-white">
</i> Add Identifier</a>
<li id="Adminsys-Type" style="display: none;">Admin System Type:
<select name="Adminsys-Type" class="Adminsys-Type">
<label for="Adminsys-Type">Admin Type:</label>
<option value="0">--Select--</option>
</select>
</li>
<li id="Adminsys-Number" style="display: none;">
<input type="checkbox" class="Adminsys-Number" value="Adminsys-Number" name="Adminsys-number">
<label for="Adminsys-Number"><em>*</em>Admin System Value:</label>
<input type="text" name=Adminsys-Number>
</li>
</ul>
<input type="submit" id="button" name="submit" value="Search">
</form>
JS:
$(document).ready(function () {
var counter = 0;
$('input[name=Organization-Name]').attr('disabled', true);
$('input[name=Identification-Number]').attr('disabled', true);
$('input[name=Family-Name]').attr('disabled', true);
$('input[name=Adminsys-Number]').attr('disabled', true);
$('#pancettaForm').change(function () {
$('.Organization-Name').click(function () {
if ($('.Organization-Name').is(':checked')) {
$('input[name=Organization-Name]').val('').attr('disabled', false);
} else {
$('input[name=Organization-Name]').attr('disabled', true);
}
});
$('select[name="Identification-Type' + counter + '"]').change(function () {
var $this = $('.Identification-Number');
var $input = $this.siblings('input[type=text]');
$input.attr("disabled", false);
$input.attr("disabled", ($(this).val() == '1111') ? true : false);
});
$('.Adminsys-Number').click(function () {
if ($('.Adminsys-Number').is(':checked')) {
$('input[name=Adminsys-Number]').val('').attr('disabled', false);
} else {
$('input[name=Adminsys-Number]').attr('disabled', true);
}
});
$('.Family-Name').click(function () {
if ($('.Family-Name').is(':checked')) {
$('input[name=Family-Name]').val('').attr('disabled', false);
} else {
$('input[name=Family-Name]').attr('disabled', true);
}
});
$('#Family-Name,#Identification-Number,#Organization-Name').hide();
if ($('#person').prop('checked')) {
$('#Family-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
} else if ($('#organization').prop('checked')) {
$('#Organization-Name,#Identification-Type,#Identification-Number,#Adminsys-Number,#Adminsys-Type,#addRow,#removeRow').show();
}
});
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
$('<div/>', {
'class': 'extraPerson' + counter,
'id': 'extraPerson' + counter,
html: GetHtml() + '</i> Remove Identifier'
}).hide().appendTo('#container').slideDown('slow');
counter++;
});
$("#container").on('click', '.removeRow', function () {
//$("#extraPerson"+counter).remove();
if (counter < 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$(this).parent().remove();
});
function GetHtml() {
// var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
if (counter == 0) {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
counter++;
return $html.html();
} else {
$html.find('[name=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[id=Identification-Number]')[0].name = "Identification-Number" + counter;
$html.find('[name=Identification-Type]')[0].name = "Identification-Type" + counter;
// $html.find('[id=Identification-Type]')[0].id="Identification-Type" + counter;
// var remove='</i> Remove Identifier';
return $html.html();
}
}
})
JSFIDDLE LINK
How can I dynamically change the name of select attribute so that I can selectively enable and disable input fields in multiple rows.
Hope this will help you a bit and I hope I got it correct:
I reworked you change function which determines the select boxes and enables the input field, like this
$('.Identification-Type').change(function () {
//#Identification-Type input
/** this can be used to count the input fields and use it in a loop later **/
var $inputFields = $('.extraPersonTemplate #Identification-Type input').length;
var $idNumber = $('input[name=Identification-Number]');
var $idNumber0 = $('input[name=Identification-Number0]');
($('select[name=Identification-Type]').val() == '1111') ? $idNumber.attr('disabled', true) : $idNumber.removeAttr('disabled');
($('select[name=Identification-Type0]').val() == '1111') ? $idNumber0.attr('disabled', true) : $idNumber0.removeAttr('disabled')
})
But from my point of view, this is not a the best approach since its not very dynamically.
If you manage to count up the select[name=Identification-Type] + counter not only for one input but for both of them like <input type="text" name="Identification-Number0"> and <input type="text" name="Identification-Number1"> it would be possible to include a loop within in this change function and loop over the $inputFields which are found
http://jsfiddle.net/xKL44/2/ this has helped me in the past... Try it out!
$('#wow').change(function() {
// Remove any previously set values
$('#show_box, #total_box').empty();
var sum = 0,
price;
$(this).find('option:selected').each(function() {
// Check that the attribute exist, so that any unset values won't bother
if ($(this).attr('data-price')) {
price = $(this).data('price');
sum += price;
$('#show_box').append('<h6>' + price + '</h6>');
}
});
$('#total_box').text(sum);
});