Disable Select based on another element on the Same Row - javascript

In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}​
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/

i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example

var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/

You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});

Related

Having Button not run Function With Empty Input Field

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}

If select input equals value do this, if it is changed remove those changes

I have a select box called "requestHistoryRequestType". I'm trying to write some jQuery so that when the value of that select box is changed I call a function that adds a class and attribute to a field and appends a span to the field that I pass in as a parameter.
The problem is if a user chooses EXPAPP or EXPDEN but then changes their selection to NA it should remove the added stuff from the previous fields and add the same stuff to a different field. Kinda hard to explain, but ask questions away! I'm kinda new to writing complex jQuery like this.
The function that does the adding classes and such:
function requiredField(requiredField) {
$(requiredField).parent().addClass('has-error');
$(requiredField).attr('data-rule-required', true);
$("label[for='" + requiredField.replace('#', '') + "']").append("<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>");
}
The actual on change listener:
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
if ($("#requestHistoryRequestType").val() === "EXPAPP" || $("#requestHistoryRequestType").val() === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if ($("#requestHistoryRequestType").val() === "NA") {
requiredField("#requestHistoryComments");
}
});
Thanks Stack!
Create a function that would remove the added stuff from all fields and call it before requiredField() calls:
function removeRequiredFields()
{
var $fields = $("#requestHistoryVerbalDateTime, #requestHistoryWrittenDateTime, #requestHistoryComments");
$fields.parent().removeClass('has-error');
$fields.attr('data-rule-required', false);
$fields.each(function() {
$("label[for='"+$(this).attr('id')+"']").find("[title='Required Field']").remove();
});
}
Or you can pass $fields from the event handler to removeRequiredFields() instead of hardcoding it there, for added flexibility.
I would just have a separate function for when you select a "NA" rather then trying to build that functionality into the same function.
I'll rewrite your event handler to make it a bit cleaner as well (IMO).
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
var selectedVal = $(this).val();
if (selectedVal === "EXPAPP" || selectedVal === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if (selectedVal === "NA") {
requiredField("#requestHistoryComments");
}
});
This way you are not hitting the DOM a potential 3 time to test your conditions every time an event is triggered. A minor change but probably a useful one as you get into more complex and larger jQuery selectors.
Edit: If you feel you MUST do it in one function then you can call the function with both elements you want to append
function requiredField(requiredField1, requiredField2) {
if (requiredField2 != null){
$(requiredField1,requiredField1).parent().addClass('has-error');
$(requiredField1,requiredField1).attr('data-rule-required', true);
var requiredLabel = "<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>"
$("label[for='" + requiredField1.replace('#', '') + "']").append(requiredLabel);
$("label[for='" + requiredField2.replace('#', '') + "']").append(requiredLabel);
}
else {
//remove multiple element classes and add it to the single one representing the "NA"
}
}
This is based on you only ever having one case where you would be passing a single "requiredField" on a case of a "NA"

Hide text area based on selection - Jquery

Here's what I'm trying to do. When the page loads, the option "Self" will be selected and there will be no text area next to it. When the user chooses "Other" then the text area will show up next to it. Any help would be much appreciated. I've been stuck on this for a bit and I'm about to pull out what hair I have left.
Here is my code.
HTML
<select name="employee_choice" id="employee_choice" data-role="slider" data-theme="c"data-track-theme="a">
<option value="0">Self</option>
<option value="1">Other</option>
</select>
<input type="text" id="pernr" name="pernr" width="12em" />
JS
$('#employee_choice').change(function(){
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
pernrField.hide();
if (empSelect == '1'){
pernrField.show();
}
if (empSelect == '0'){
pernrField.hide();
}
});
Just toggle the input's visiblity based on the selects value :
$('#employee_choice').on('change', function() {
$('#pernr').toggle(this.value==='1');
});
FIDDLE
you need to check on the selected value.
var empSelect =$('select[name="employee_choice"]').val()
and instead of multiple if you can use else too
You need to run it first when the page loads. As seen in this jsFiddle, your code does work if you change the JavaScript to the following:
function showOrHidePernr() {
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
pernrField.hide();
if (empSelect == '1') {
pernrField.show();
}
if (empSelect == '0') {
pernrField.hide();
}
}
$('#employee_choice').change(showOrHidePernr);
$(function() {
showOrHidePernr();
});
First initialize the status, and also on the change() event:
show_pernrfield();
$('#employee_choice').change(function(){
show_pernrfield();
});
function show_pernrfield() {
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
if (empSelect === '1') {
pernrField.show();
}
else {
pernrField.hide();
}
}
Take a look: http://jsfiddle.net/YhaCh/1/
Try using console.log() to examine values of your variables - then it will become apparent which actions your script takes.

Show button if input is not empty

I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>​
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});

Categories

Resources