JavaScript hide element function - javascript

I have a form where the user can select a generic auto-population based on checking a radio button. When the user checks the auto-populate radio button, the fields are auto populated with the data and then the fields become disabled.
In this first part of the function, I pass the auto-filled data:
$('#myOptions').click(function()
$('#value1').val("Auto-filled data");
$('#Value2').val("Auto-filled data");
$('#Value3').val("Auto-filled data");
In this second part, I am disabling the html inputs
// now i am disabling the html inputs:
$('#Value4').prop("disabled", true);
$('#Value5').prop("disabled", true);
$('#value6').prop("disabled", true);
Suppose I have another field with an ID of "Value7" in the form, that I would like to hide from the user interface as part of this function.
How can I hide the "Value7" input upon function triggering? I appreciate the help, I am very new to JavaScript, though I find it very exciting!

Using jquery:
To hide
jQuery('#Value7').hide() or jQuery('#Value7').css("display","none")
To show the element back
jQuery('#Value7').show() or jQuery('#Value7').css("display","block")
or pure js:
javascript hide/show element

Try this javascript:
if you want disable:
document.getElementById('#Value7').setAttribute("disabled","disabled");
if you want enable:
document.getElementById('#Value7').removeAttribute('disabled');
if you want to hide :
document.getElementById('#Value7').css("display","none");
if you want to show:
document.getElementById('#Value7').css("display","block");

I am not getting what are you trying to ask actualy .
Let me know if this helps -
$("Value7").hide()

Related

validate error message not displaying for drop down list when not selected

Please bear with me as I am not sure what I have done wrong here:
Basically I have a form and I have some drop down lists.
If I hard code the select list for my drop down list with styleClass="requiredinpfield" then I will get a proper validation error message pops up below the select list whenever I don't select an option from the list and if I try hit submit button.
However, because some of the drop down lists are not always required (they only required when certain option was selected) so in this case I am not hard coding these select lists to have styleClass="requiredinpfield" but instead I am using jQuery to dynamically add the requiredinpfield class to the list object whenever an associate radio button was selected.
The problem I am having now is this won't show the validation error message when I don't select any option and try to hit the Submit button. It prevent me from continue, however. Its just I don't get to see the error message. Can you see what I have done wrong?
Here is an example of how I use jQuery to add the requiredinpfield class and it is not showing me the validation error message when needed:
HTML
<div id="fruitDivId">
<apex:inputField id="testPickList" value="{!PickTheFruitYouLike__c}" styleClass="selectpicker"/>
</div>
A radio button to confirm that the list is needed
<apex:selectRadio value="{!DoYouLikeFruit}" onchange="whenAnOptionWasSelectedAndINeedToAddRequiredInpField(this.value,'fruitDivId');" styleClass="requiredinpfield radio pa-cus pa-cus-other">
Script to add requiredinpfield class
function whenAnOptionWasSelectedAndINeedToAddRequiredInpField(t,divId)
{
if (t == 'Yes' ){
$('[id$='+divId+']').show();
$('[id$="testPickList"]').addClass('requiredinpfield');
}
else{
$('[id$='+divId+']').hide();
$('[id$="testPickList"]').removeClass('requiredinpfield');
}
}
Script to validate
Note: my submit button will trigger the !checkRequired() method.
function checkRequired(){
var isValidate = true;
//$('.errorIcon').css('opacity', '0');
$('.requiredinpfield').each(function(){
if($(this).is("select") && $(this).val() == ''){
/*alert("Hello!!");*/
if(!($(this).next('.requiredinpfield').first().next('.errorMsg').size()>0)){
console.log($(this).next('.requiredinpfield'));
$(this).next('.requiredinpfield').first().after('<div class="errorMsg"><strong></strong> You must select an option</div>');
}
isValidate = false;
}
else{
if($(this).is("select") && (($(this).next('.requiredinpfield').first().next('.errorMsg').size()>0)))
{
$(this).next('.requiredinpfield').first().next('.errorMsg').remove();
}
}
});
//alert(isValidate);
return isValidate;
}
Assuming that the rest of the code is correct, the problem might in the way you are selecting elements by ID
in jQuery, to select an element by id simply write
$('#idoftheelement')
so in your whenAnOptionWasSelectedAndINeedToAddRequiredInpField function,
try replacing
$('[id$='+divId+']')
with
$('#'+divId)
do the same at all locations where you are selecting by id.

jQuery: set / reset form fields with certain class (improve code)

I am new to jQuery and hope someone here can help me with this.
I have a large HTML form with a hidden div ('#requestDetails').
Within this div there are checkboxes, radio buttons and selects with a certain class on a specific value ('.hiddenDefault') which is used to only apply a default value when they are visible.
Now I have a certain event that shows this div and another one that hides it again.
When showing the div I want to set the above default values.
When hiding it I want to reset the fields, incl. all input fields within that div (i.e. uncheck / unselect them and remove any default or entered values).
I have the following code which looks ok to me at first glance but I would like to know if this is proper / valid code, if I am missing anything here and if there is a better / faster way to achieve the same.
My jQuery:
$('[name=requestType]').on('change', function(){
if($(this).hasClass('triggerDiv')){
$('#requestDetails').find('.hiddenDefault').each(function(){
// set default values + show div
$(this).not('select').prop('checked', true);
$(this).not('input[type=checkbox], input[type=radio]').prop('selected', true);
});
$('#requestDetails').show();
}else{
$('#requestDetails').find('input, select').each(function(){
// empty / reset fields + hide div
$(this).find('input[type=checkbox], input[type=radio]').prop('checked', false);
$(this).find('input').not(':button, :checkbox, :hidden, :radio, :reset, :submit').val('');
$(this).find('select').prop('selected', false);
});
$('#requestDetails').hide();
}
});
Many thanks in advance for any help with this,
Mike
Just improving syntax or style of code you have written:
$('[name=requestType]').on('change', function(){
if($(this).hasClass('triggerDiv')){
// show div + set default values
$(this).not('select').prop('checked', true);
$(this).not('input[type=checkbox], input[type=radio]').prop('selected', true);
$('#requestDetails').show();
}else{
// hide div + reset fields
$('#requestDetails').find('input[type=checkbox], input[type=radio], input, select').not(':button, :checkbox, :hidden, :radio, :reset, :submit').val('').prop('checked', false);
$('#requestDetails').hide();
}
});
Sorry have not checked syntax, so correct me if I am wrong at it.
Not this will improve performance as well as you have written inside each.

ASP MVC binding two controls to one field

In my view model I have a field. This field can be selected from a drop down list or entered in a textbox. I have two radio buttons which allows to select between drop and textbox.
<div class="frm_row" id="contractorRow">
#Html.RadioButton("IsContractorNew", "false", true)
#Html.Label(#Resources.SomeLabels.Existing)
#Html.RadioButton("IsContractorNew", "true", false)
#Html.Label(#Resources.SomeLabels.New)
<div class="frm_row_input" id="contractorDropDownList">
#Html.DropDownListFor(model => model.CONTRACTOR, Model.Contractors)
#Html.ValidationMessageFor(model => model.CONTRACTOR)
</div>
<div class="frm_row_input" id="contractorTextBox" style="display: none;">
#Html.TextBoxFor(model => model.CONTRACTOR)
#Html.ValidationMessageFor(model => model.CONTRACTOR)
</div>
</div>
I prepared a javascript code for hiding, showing and clearing controls while selecting radio buttons. The problem is - field is bound only to the first control (drop down list).
EDIT:
I solved this problem by creating one hidden field and scripting whole logic to bind active control with it and therefore with the model. Anyway if anyone knows simpler solution, please post it.
I know this is an old question, but for those dealing with this issue, here's a solution:
Explanation
When a form is submitted, input elements are bound to the model by their name attribute. Let's say you use HTML helpers to generate your form, and you generate two input fields which bind to the same property on the model. When rendered to the DOM, they both have the same name attribute.
<input name="Passport.BirthPlace" id="birthPlaceDropDown" ... >
<input name="Passport.BirthPlace" id="birthPlaceInfoTextbox" ... >
When the form is submitted, it will bind the first (in the DOM) input it finds to Passport.BirthPlace
A Solution
The quick and easy way to fix this is to use JQuery to change the name of the field you don't want bound on submit. For me, I use a checkbox to toggle which field shows. When the checkbox changes, I hide one control, change its name attribute, and show the other one (and change it's name attribute to Passport.BirthPlace) It looks like this, basically:
First, I run this on document ready
$('#birthPlaceInfoTextbox').attr('name', 'nosubmit'); // Change name to avoid binding on inactive element
Then, I create a listener for my checkbox which toggles which control should be bound:
$('#notBornUSCheckbox').change(function() {
if (this.checked) {
// Not born us was checked, hide state dropdown and show freeform text box
$('#stateDropDownSection').addClass('d-none'); // Hide drop down
$('#birthPlaceDropDown').attr('name', 'nosubmit'); // Change name to something other than Passport.BirthPlace
$('#birthPlaceInfoTextbox').attr('name', 'Passport.BirthPlace'); // Set this one to be bound to the model
$('#stateTextboxSection').removeClass('d-none'); // Show the textbox field
} else { // Opposite of above lines
$('#stateDropDownSection').removeClass('d-none');
$('#stateTextboxSection').addClass('d-none');
$('#birthPlaceInfoTextbox').attr('name', 'nosubmit');
$('#birthPlaceDropDown').attr('name', 'Passport.BirthPlace');
}
});
Instead of using Razor #Html.TextBoxFor... for your textbox, you could try using raw HTML e.g. <input />. Also, have your JavaScript code remove the other field from the DOM entirely when a radio button is clicked, before submitting the form.

Radio button REQUIRED if input field has content

I have a a reasonably quick problem to solve (I think). I have a form online and it validates the required content for the user's data, but has no validation on the first part of the form.
I've been asked however if I can make a radio button REQUIRED depending on whether an input field has been filled in.
The form can be found here:
http://www.elcorteingles.pt/reservas/livros_escolares/form.asp
So if the person start's filling in the input fields on the first line, that the radio buttons in the group become REQUIRED (for either the CDROM ou CADERNO but not both)
You can handle the focusout and blur events for the input:
$(function () {
// Handle every input type text.
// To select specific inputs, give them a common class and change the
// selector accordingly.
$("input[type=text]").on("focusout blur", function () {
// Check for inputs with class radio_btns which are in
// the parent element (li).
// Set their required property.
$(this).parent().find("input.radio_btns")
.prop("required", $(this).val().trim().length > 0);
});
});
Demo
jQuery reference (Tree Traversal)
jQuery reference (.prop())
jQuery reference (.focusout())
jQuery reference (.blur())
This will work. You can include the following JQuery code in the script tag, and also the JQuery cdn link in the head tag.
$(document).ready(function(){
$('#01titulo').focusout(function(){
if ($(this).val() !== "") {
$('[name="01caderno"]').prop('required', true);
} else {
$('[name="01caderno"]').prop('required', false);
}
alert($('[name="01caderno"]').attr('required'));
});
});
Try using the following js code its working:
$(document).ready(function(){
$(".titulo_books").each(function(){
$(this).focus(function(){
var radioChecked=0;
var currElemId = parseInt($(this).attr('id'));
var radioSelecterId = (currElemId>9) ? currElemId : "0"+currElemId;
$("input:radio[name="+radioSelecterId+"caderno]").each(function(){
if(radioChecked==0)
{
radioChecked==1;
$(this).attr("checked","checked");
}
});
});
});
});
I have checked it by executing this from console on your site and it seems to work fine. You can alter this in the way you want. I have checked one of the four available radio button. User can change the input value if required. Or you can also change the default radio button selected through my code.

How do I use jQuery to disable a form's submit button until every required field has been filled?

I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are filled with a value. And after they are all filled, should a field that WAS field get erased by the user, I would like the submit button to turn back to disabled again.
How can I accomplish this with jQuery?
Guess my first instinct would be to run a function whenever the user starts modifying any of the inputs. Something like this:
$('#submitBtn').prop('disabled', true);
$('.requiredInput').change(function() {
inspectAllInputFields();
});
We then would have a function that checks every input and if they're validated then enable the submit button...
function inspectAllInputFields(){
var count = 0;
$('.requiredInput').each(function(i){
if( $(this).val() === '') {
//show a warning?
count++;
}
if(count == 0){
$('#submitBtn').prop('disabled', false);
}else {
$('#submitBtn').prop('disabled', true);
}
});
}
You may also want to add a call to the inspect function on page-load that way if the input values are stored or your other code is populating the data it will still work correctly.
inspectAllInputFields();
Hope this helps,
~Matt
Here's something comprehensive, just because:
$(document).ready(function() {
$form = $('#formid'); // cache
$form.find(':input[type="submit"]').prop('disabled', true); // disable submit btn
$form.find(':input').change(function() { // monitor all inputs for changes
var disable = false;
$form.find(':input').not('[type="submit"]').each(function(i, el) { // test all inputs for values
if ($.trim(el.value) === '') {
disable = true; // disable submit if any of them are still blank
}
});
$form.find(':input[type="submit"]').prop('disabled', disable);
});
});
http://jsfiddle.net/mblase75/xtPhk/1/
Set the disabled attribute on the submit button. Like:
$('input:submit').attr('disabled', 'disabled');
And use the .change() event on your form fields.
Start with the button disabled (obviously). Bind an onkeyup event to each required text input, and an onchange or onclick to the select boxes (and any radio buttons/checkboxes), and when it fires, check whether all required inputs are filled. If so, enable the button. If not, disable it.
There is one loophole here, though. Users can delete the value of a text field without triggering the onkeyup event by using the mouse to "cut" the text out, or by holding down the delete/backspace key once they have deleted it all, and clicking the button before deleting it.
You can get around the second by either
disabling the button with onkeydown and checking if it is ok on onkeyup
checking for validity when the button is clicked
An idea from me:
Define a variable -with global scope- and add the value true- Write a submit function within your check the value above varibale. Evalue the the submit event only, if the value is true.
Write a function which ckecks all value from input fields and select fields. Checking the length of value to zero. if the value length of one field zero then change the value of the global variable to false.
After that, add to all input fields the event 'onKeydown' or 'onKeyUp' and to all select boxes the event 'onChange'.
I recommend taking a slightly different approach and using jquery's validation http://docs.jquery.com/Plugins/validation. The tactic you are suggesting is prone to security holes. The user could easily using firebug enable that button and then submit the form.
Using jquery validation is clean and it allows you to show error messages under the required fields if so desired on submit.

Categories