Checking if input value isn't empty working as wanted - javascript

I have a few input fields that must be filled before some button becomes active. My code does this, but only works after filling all inputs fields I changed selection from last filled input field to any other. How to make it more dynamic and allow button to become active without changing selection?
$(function() {
$('body').on('change','#form2',function(){
if($("#name").val() != "" && $("#number").val() != "" && $("#shortname").val() != "")
{
$('#CreateConnections').removeAttr("disabled");
}
else
{
$('#CreateConnections').attr("disabled", true);
}
});
})

You can try binding both keyup and change to all input elements. Also:
instead of using != to evaluate the value, we can simply check the value itself: when not empty it will return true, without the need to make comparisons.
you should use .prop() when working with boolean attributes, like disabled, checked, readonly, selected and the likes, instead of .attr(). p/s: You should also avoid using .removeProp() or .removeAttr() whenever possible, as once removed they cannot be added back.
Here is the updated jQuery:
$(function() {
$('body').on('change keyup','#form2 :input', function() {
if($("#name").val() && $("#number").val() && $("#shortname").val()) {
$('#CreateConnections').prop("disabled", false);
} else {
$('#CreateConnections').prop("disabled", true);
}
});
});
Here is a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/7rK2p/

Related

Setting and removing the 'required' attribute using javascript and html5

I have this function, all im trying to do is if the first radio button is selected, then hide a few input fields and make them not required by the form. Then is the other radio button is selected then show those hidden fields and make them required by the form. The user may change between the radio buttons, and so the show hide operation and adding and removing of the required attributes have to happen on radio button change. At the moment the fields are showing and hiding but i cannot change the required attributes. Any ideas? Thank you.
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
$('#1041827741').setAttribute("required", "");
$('#1283215174').setAttribute("required", "");
$('#1496644528').setAttribute("required", "");
$('#1392644643').setAttribute("required", "");
$('#1321281340').setAttribute("required", "");
}
else {
$('#show-me').hide();
$('#1041827741').removeAttr('required');
$('#1283215174').removeAttr('required');
$('#1496644528').removeAttr('required');
$('#1392644643').removeAttr('required');
$('#1321281340').removeAttr('required');
}
});
});
Use the prop() method:
$('#1041827741').prop('required',true);
You could use .prop("required", true / false) to set and remove. Also, setAttribute and removeAttribute methods are native DOM methods which directly operate on the element.
If you do not have an option of changing the elements markup you could modify your code to save some typings.
Here is what you could do to fix.
$(document).ready(function() {
$('input[type="radio"]').click(function() {
var ids = ["#1041827741", "#1283215174", "#1496644528", "#1392644643", "#1321281340"];
if ($(this).attr('id') === 'watch-me') {
$('#show-me').show();
ids.forEach((id) => $(id).prop("required", true));
} else {
$('#show-me').hide();
ids.forEach((id) => $(id).prop("required", false));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
if you do have options to change the elements, I would assign a same class name to all of those elements and just operate on the ids.
Here is what it can be done.
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr('id') === 'watch-me') {
$('#show-me').show();
//inputElement is the class assigned to all input elements
$(".inputElement").prop("required", true);
} else {
$('#show-me').hide();
$(".inputElement").prop("required", false);
}
});
});

jQuery get / set value of textbox value in a repeater

I have a repeater with textboxes ID="txtBomName" in an ascx page with a value retrieved from datatable on pageload.
the end user can change the value, must be not be null/empty.
I have jquery to check if null/empty on change or blur, produce alert if null then I would like the null value set back to original else set value as user entered.
This does work if, I use the generated control ID i.e:
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName)"
this obviously only works for the the first textbox on the page, as the "ct100" part of the ID changes for each box.
code:
$(document).ready(function () {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").change(function () {
var oldVal = this.getAttribute('value');
if (this.value == null || this.value == "") {
alert("Please ensure the name is not empty");
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(oldVal);
}
else {
$("#p_lt_ctl02_pageplaceholder_p_lt_zoneMainContent1_BOM_rptBoms_ctl00_txtBomName").val(this.value);
}
});
});
so, I changed the code to look for id$=txtBomName and set an alert to (this.id) the id for each box shows correctly, how can I set the value of the textboxes using (this.id).val(oldVal); ?
You need to use:
$(this).val(oldVal);
'this' is a reference to the current object i.e. textArea the abouve code will set the value of the textArea
Try this code
$(document).ready(function () {
// The simplest way is to save the original value using data() when the
// element gets focus.
$("input[id$='txtBomName']").on('focusin', function(){
$(this).data('val', $(this).val());
});
$("input[id$='txtBomName']").change(function () {
var txtBox=$(this);
var prev = txtBox.data('val');
var current = txtBox.val();
if (current) {
txtBox.val(current);
}
else {
alert("Please ensure the name is not empty");
txtBox.val(prev);
}
});
});

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

Javascript iterate through all checkboxes on submit, and set attribute if changed from original value

I am trying to make a javascript function similar to the following, except it will iterate through all the checkboxes when the user clicks the submit button:
$('.checkboxstatus').click(function(){
this.setAttribute('checked',this.checked);
if (this.checked && $(this).data("def") == 0){
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else if(!this.checked && $(this).data("def") == 'checked')
{
//checkbox has changed
this.setAttribute('changed', 'yes');
}
else{
//no change in checkbox
this.setAttribute('changed', 'no');
}
});
When the user clicks submit, the function should be called and it should iterate through all checkboxes and see if the checkbox is checked and see if the data-def is checked or 0. If the checkbox is checked and data-def="checked" then nothing should happen. If the checkbox state is different from the data-def then an attribute ("changed") should be added to that checkbox with value of "yes". Any suggestions on how to go about this?
Your question almost gives you the answer. You need to attach a "submit" event handler to the form, then grab all input[type=checkbox] and set the "changed" attribute accordingly.
I'm not sure I get this, but the usual way to do something like this would be to set an initial state in data, then on submit, prevent the submit action, check all the checkboxes against that initial state data variable, and see if anything changed, if it did, trigger the native submit handler ?
var boxes = $('input[type="checkbox"]').each(function() {
$(this).data('initial_state', this.checked);
});
$('form').on('submit', function(e){
e.preventDefault();
var same_same = true;
boxes.each(function() {
if ( $(this).data('initial_state') !== this.checked ) { // has changed ?
$(this).data('changed', true);
same_same = false;
}
});
if ( ! same_same ) { // diffelent
this.submit();
} else {
alert('same same, but not diffelent!');
}
});

Hide buttons related to empty textareas (selecting issue)

I'm struggling with a jQuery selection: I have a table that contains these columns (more or less)
Name (input field)
Surname (input field)
Note (textarea)
Button (a button to submit the relative note)
I would like to hide all buttons whose textarea is empty (to avoid the submission). This is the table:
The DOM structure of the single row is quite simple (I think):
So, I would like to select something like "all buttons contained in a td that is a brother of a td that cointains an empty textarea"...anf anf...can I do that with a single jQuery selection or not? Thank you in advance.
Of course!
$("tr td textarea").each(function() {
if (this.value == "") {
$(this).closest("td").next("td").find("button").prop("disabled", true);
}
});
You could hide buttons onLoad with the next selector:
$('textarea:empty').parent().next('td').find('button').hide();
Or if you want to disable the buttons:
$('textarea:empty').parent().next('td').find('button').prop("disabled", true);
It would be useful to check if user has type something in the textarea while on the page, and enable or not the button:
$( $('textarea') ).blur(function() {
var button = $(this).parent().next('td').find('button');
if($(this).val() === ''){
button.prop("disabled", true);
}else{
button.prop("disabled", false);
}
});
You can check this fiddle with your table included:
http://jsfiddle.net/6B9XA/4/
try this
$('table textarea').change(function()
{
var thisval=$.trim($(this).html())
if(thisval=='')
{
$(this).parent().next().children('button').attr('disabled')
}
})
I think you should use it this way:
$("#yourtableid").find("textarea").each(function() {
if (this.value == "") {
$(this).closest("tr").find("button").prop("disabled", true);
}
});
"#yourtableid" this should be changed to your table id.
Selectors optimization for performance boost.
You can use filter() to get only the buttons who contains an empty textarea within that row
$('tr button').filter(function(){ // get all buttons
return $(this).closest('tr').find('textarea').val() == ''; // only return those that are empty
}).prop('disabled',true); // disable the buttons

Categories

Resources