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

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);
}
});
});

Related

Disable and enable function in Jquery

I have a text input in html that is affected by a function exectued by .change() events from different radios and checkboxes. I'm trying to make it so that if a user types into the input, this function will no longer run when a .change() event happens in the aforementioned radios and checkboxes (the user must still be able to use these radios and checkboxes). However, if the user leaves the input blank and clicks away, the script will run again. I hope is possible.
Here is my take on this so far:
Using.prop('diabled' isnt viable because it completely disables the input, making the user unable to type in it, so I need another solution.
$(function() {
$('#burger-navn').on('input', function() {
$("#burger-navn").prop('disabled', true);
});
//When the input (#burger-navn) is typed into it should be "disabled"
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#burger-navn").prop('disabled', false);
}
});
//But if its clicked out of while its blank, it should be able to run again.
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if (!$("#burger-navn").not(':disabled')) { //condition that tests
navngenerator();
}
});
});
To solve this I simply created a separate input tag that I could add and remove disabled attribute from, and check if it has that attribute.
So in html:
<input id="burger-navn" type="text"/>
<input id="toggle" disabled="disabled" style="display:none"/>
jQuery:
var previousValue = $("#burger-navn").val();
$("#burger-navn").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
$("#toggle").prop('disabled', false);
}//This function will remove disabled from #toggle, when a user types into #burger-navn
});
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#toggle").prop('disabled', true);
}
});
if ($("#toggle").is(':disabled')) {
navngenerator();
}
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if ($("#toggle").is(':disabled')) {
navngenerator();
}
});
$(selector).on('change', function(event){
event.preventDefault();
event.stopPropagation();
// the selected field no longer does anything on change
});
is that what you are looking for?

Checking if input value isn't empty working as wanted

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/

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

each() with multiple ids or classes?

I have a form with 15 fields(including input types,select box,text area).
I can write a function to validate this form by the ordinary way,but thats not smart coding.I need to use each in this case.
This is what I was thinking:
$("#id1, #id2, #id3... #id15").each(function(){
if ($(this).val == "") {
$(this).closest("#error").css("display", "block");
}
})
Should this validation be class based or id based,am I going the right way?Am i using each() in the right context?
You can use :input selector here to select all the input elements inside the form like:
$("#formID :input").each(function () {
if ($(this).val() == "") {
$(this).closest("#error").css("display", "block");
}
});
Or maybe add a specific class to all the inputs that you want to validate like validate and do like:
$(".validate").each(function () {
if ($(this).val() == "") {
$(this).closest("#error").css("display", "block");
}
});
Documentation: http://api.jquery.com/input-selector/
Description: Selects all input, textarea, select and button elements.
Or any tag with id attribute inside the form
$('form *[id]')
or name attr would even better
$('form *[name]')
If you have multiple inputs, selects and form elements, add a class like "input-group" to each element and then iterate over that group.
$("form .input-group").each(function(){
if ($(this).val == "") {
$(this).closest("#error").css("display", "block");
}
})

Select individual form with Javascript

<script>
$(document).ready(function() {
$('form["meldaan"] input').keyup(function() {
var empty = false;
$('form["meldaan"] input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
});
</script>
This script works fine with one form, but I have two or three different forms on one page. I want each form to be treated different, if I use this code all fields in ALL forms need to be filled in, which I obviously don't want.
How can I identify the unique forms? Say one form is named name="formone" and the other name="formtwo". How would I implement that? (It's okay if I have to make more functions).
You just need to adjust your selector:
$('form[name="formone"] > input')
Update: #Andre, in your live example inputs are not direct children of the form element, so you need to use:
$('form[name="formone"] input')
Update 2: if you are using an id:
$('#formid input')

Categories

Resources