Disable the other textbox if the textbox(4) is filled. I have a multiple text boxes in my div
For instance:
If I put a text in textbox(4), then the textbox(1) will becomes disable. Then if I remove the text in the textbox(4), then the text box for the textbox(1) will becomes enable.
Here is the sample html:
<div class="main-wrapper">
<div class="form-text-wrapper">
<div><input type="text" class="form-text" value="" name="text1" id="text1"></div>
<div><input type="text" class="form-text" value="" name="text2" id="text2"></div>
<div><input type="text" class="form-text" value="" name="text3" id="text3"></div>
<div><input type="text" class="form-text" value="" name="text4" id="text4"></div>
</div>
</div>
My code doesn't seems to work, I'm not sure what's wrong with my code.
Here is my js code:
$('.main-wrapper').each(function(){
var name = $('#text4', this).val();
var disForm = $('#text1');
if ($(name.length >= 1)) {
$(disForm, this).attr('disabled', 'disabled');
} else {
$(disForm, this).removeAttr('disabled');
}
});
Please help... Thank you!!!
jQuery(function($) {
//change event handler which gets executd whenever the value of #test4 is chaned
$('#text4').on('change', function() {
//find all the input elements under the current .form-text-wrapper and except #test4 and set its disabled status based on #text4's value
$(this).closest('.form-text-wrapper').find('input').not(this).prop('disabled', this.value.length)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="main-wrapper">
<div class="form-text-wrapper">
<div><input type="text" class="form-text" value="" name="text1" id="text1"></div>
<div><input type="text" class="form-text" value="" name="text2" id="text2"></div>
<div><input type="text" class="form-text" value="" name="text3" id="text3"></div>
<div><input type="text" class="form-text" value="" name="text4" id="text4"></div>
</div>
</div>
Ok, so a few issues with what you are doing.
Firstly you are needing to execute your code every time one of those text boxes changes. You can wrap that functionality into a function and add it to the change event on each of the textboxes. I have added an example below. NB the example could be alot better than explicitly adding the change to each of the textboxes but I'll leave that for you to do.
Secondly you were executing your comparison for if the length was greater than 0 inside a jquery wrapper ($(name.length >= 1)) -> Don't. I've removed that as well in the code sample.
Thirdly I'm a little confused by the requirement. Are you wanting it to toggle disabled/not disabled for just the first text box? REading your code that's what it looked like you were trying to achieve. If you are wanting to disable all of the rest of the text boxes then Arun P Johny's function will do what you want.
function onTextChange(){
console.log('running');
$('.main-wrapper').each(function(){
var name = $('#text4', this).val();
var disForm = $('#text1');
if (name.length >= 1) {
$(disForm, this).attr('disabled', 'disabled');
} else {
$(disForm, this).removeAttr('disabled');
}
});
}
$('#text1').on('change', onTextChange);
$('#text2').on('change', onTextChange);
$('#text3').on('change', onTextChange);
$('#text4').on('change', onTextChange);
http://jsfiddle.net/jtgs5kcj/1/
Related
<input name="checkthis" type="checkbox">
<span>text here</span>
<input type="text" name="checkthis">
<input type="text" name="another">
<input type="text">
<input type="checkbox">
<input type="text" id="eventTarget" oninput="findPreviousInputcheckboxCheckthis">
How to get previous input checkbox with name "checkthis" using queryselector on an element?
function findPreviousInputcheckboxCheckthis(ev) {
checkboxCheckthis = ev.target.querySelector( "input[name='checkthis']);
}
Edit: There are many more input checkboxes with name="checkthis" before and after the snippet I posted. They are nested in other element also.
I simply want the nearest previous checkbox in the html-source starting from the target, nested or not.
Based on your below comment, I have updated the answer snippet where you need to add parent div structure and then you can find the checkthis name attribute quickly. Please check below working snippet:
function findPreviousInputcheckbdfoxCheckthis(ev) {
var selectElement = document.getElementById(ev);
selectElement.querySelector('input[name="checkthis"]').style.visibility = "hidden";
}
<div id="div1">
<input name="checkthis" type="checkbox" value="previous">
<span>text here</span>
<input type="text" name="checkthis">
<input type="text" name="another">
<input type="text">
<input type="checkbox" value="next">
<input type="text" id="eventTarget" oninput="findPreviousInputcheckbdfoxCheckthis(this.parentElement.id)" placeholder="Previous checkbox">
</div>
Here, I have added div1 id and you can repeat the same by using using ID and rest the JavaScript will be same and it will find your first previous "name=checkthis" checkbox.
Hope this solution will be work for you!
Also, below is the link where I have used multiple repeat structure. Please refer it also:
https://jsfiddle.net/kairavthakar2016/3d8g49nm/96/
I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value)
alert(field.name + ' is required');
});
console.log(fields);
}
</script>
If anyone can work out how to include validation of check boxes, it would be much appreciated.
Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name">
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
$.each(fields, function(i, field) {
field=$(field).find('input, select, textarea')[0]
if (!field.value || (field.type=='checkbox' && !field.checked))
alert(field.name + ' is required');
});
}
</script>
The problems were:
serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
Checkboxes don't have a property value, instead they are checked
There is more than one way to determine this:
Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:
if($("input[name='Check_0']:checked").length === 1)
Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.
if(!$("input[type='checkbox']")[0].checked)
NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you
should always do a second round of validation on the server that will
be receiving the data.
FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="userName" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
alert(field.name + ' is required');
}
});
// Check to see if the input is a checkbox and if it's checked
if(!$("input[type='checkbox']")[0].checked){
alert("You must agree to the terms to continue.");
}
}
</script>
Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.
Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.
If you're interested, here's your code without JQuery:
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="name" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
// Get all the required elements into an Array
var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
// Loop over the array:
fields.forEach(function(field) {
// Check for text boxes or textareas that have no value
if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
&& !field.value){
alert(field.name + ' is required');
// Then check for checkboxes that aren't checked
} else if(field.type === "checkbox" && !field.checked){
alert("You must agree to the terms to continue.");
}
});
}
</script>
I have a working Code-pen, the calculated results are showing on next to input fields SPAN. I tried to get that calculated value from SPAN and overwrite the input fields.
<!-- Include this line of code --><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtx1" /><br />
<span id="txtSpan"></span>
<input type="button" value="Appended-textBox" id="Btn3" />
and the JS
$(document).ready(function() {
$('#Btn3').click(function() {
var txtvalue = $('#txtx1').val();
$("#txtSpan").text(txtvalue);
console.log(txtvalue);
});
});
The above works I just want to other way around setting the Input with changing SPAN value.
Is there any way I can overwrite the input box with calculated SPAN values and for the final SPAN result to write to input (ID=GrandTotal),
<div>
<label class="description" for="Coconut">Coconut</label>
<input id="Coconut" name="Coconut" class="element text medium" type="text" maxlength="255" value="10" readonly="true"/>
</div>
<div>
<label class="description" for="GrandTotal">Grand Total</label>
<input id="GrandTotal" name="GrandTotal" class="element text medium" type="text" maxlength="255" value="" readonly="true"/>
</div>
Many thanks and sorry to consume your time. many thanks in advance
https://codepen.io/dunya/pen/mojKNz
I managed to fix it by adding below line:please check the working version above pen.
$('#GrandTotal').val(parseInt($(this).html()));
when I tried the
$('#GrandTotal').val(sum);
it gave me the wrong calculation.
I have a website where there are five checkboxes, a div that contains another divs which each div contains five input hidden that have a value 1 or empty. That value comes from DB.
That's an example to represent the div container with the divs:
<input checkbox value="a">
<input checkbox value="b">
<input checkbox value="c">
<input checkbox value="d">
<input checkbox value="e">
<div class="container">
<div class="content" data-name="combine">
<input type="hidden" value="" data-name="a" />
<input type="hidden" value="" data-name="b" />
<input type="hidden" value="" data-name="c" />
<input type="hidden" value="" data-name="d" />
<input type="hidden" value="" data-name="e" />
</div>
<div class="content" data-name="combine">
<input type="hidden" value="1" data-name="a" />
<input type="hidden" value="" data-name="b" />
<input type="hidden" value="" data-name="c" />
<input type="hidden" value="1" data-name="d" />
<input type="hidden" value="" data-name="e" />
</div>
</div>
In the javascript code i have this snippet:
if(elementLength > 0) {
$("[data-name='combine'] div.tagsProds").each(function() {
var element = $(this);
$.each(enabledChecks,function(i, v) {
if(element.find("input[name='"+v+"']").val() == "") {
element.append("<div class='blocked'></div>");
element.unbind("click");
element.addClass("js_noSortable");
}
});
});
}
The javascript first checks if the div.container has childs and if it has childs the code iterates each child. On each child i iterate the five each checkbox (enabledChecks) and i see if the input hidden are empty. What i need if that if the five input are empty then append the `div.blocked'.
As i don't have enough reputation to write a comment i write an answer.
First, i think that your answer is quite interesting if you're looking to find a way using a jQuery function, but as i don't know any function to do this i think that you can create an array() and when you check if the input has empty value push it to the array, when the loop finishes you check the length of the array() and if it matches with the number of your checkboxes then append the .blocked
If I understand the question correctly, you want to find divs matching some selector that have no child input elements with non-empty values. The .filter method seems like a good fit here:
$("[data-name='"+name+"'] div.tagsProds")
.filter(function() {
// assert that at least one child input has a value
var $inputsWithValue = $(this).find("input[name='avail_" + v + "'][value!='']");
return $inputsWithValue.length === 0;
})
.each(function() {
// now act on those value-less divs
$(this)
.append("<div class='blocked'></div>")
.addClass("js_noSortable")
.unbind("click");
});
Another selector-only option might look like:
$("[data-name='"+name+"'] div.tagsProds:not(:has(input[name='avail_" + v + "'][value!='']))")
.each(function() {
// now act on those value-less divs
$(this)
.append("<div class='blocked'></div>")
.addClass("js_noSortable")
.unbind("click");
});
JSFiddle: http://jsfiddle.net/nrabinowitz/vrx2wk8g/
Note that the examples above follow the selectors in your sample code, but won't work against your sample markup.
The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();