Compare onclick action of two html button using javascript - javascript

I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?

This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}

Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/

Related

JS - Add class to form when input has value

I have a form with one input field for the emailaddress. Now I want to add a class to the <form> when the input has value, but I can't figure out how to do that.
I'm using this code to add a class to the label when the input has value, but I can't make it work for the also:
function checkForInputFooter(element) {
const $label = $(element).siblings('.raven-field-label');
if ($(element).val().length > 0) {
$label.addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
Pen: https://codepen.io/mdia/pen/gOrOWMN
This is the solution using jQuery:
function checkForInputFooter(element) {
// element is passed to the function ^
const $label = $(element).siblings('.raven-field-label');
var $element = $(element);
if ($element.val().length > 0) {
$label.addClass('input-has-value');
$element.closest('form').addClass('input-has-value');
} else {
$label.removeClass('input-has-value');
$element.closest('form').removeClass('input-has-value');
}
}
// The lines below are executed on page load
$('input.raven-field').each(function() {
checkForInputFooter(this);
});
// The lines below (inside) are executed on change & keyup
$('input.raven-field').on('change keyup', function() {
checkForInputFooter(this);
});
I've updated your pen here.
Here it is, using javascript vanilla. I selected the label tag ad form tag and added/removed the class accoring to the element value, but first you should add id="myForm" to your form html tag. Good luck.
function checkForInputFooter(element) {
// element is passed to the function ^
let label = element.parentNode.querySelector('.raven-field-label');
let myForm = document.getElementById("myform");
let inputValue = element.value;
if(inputValue != "" && inputValue != null){
label.classList.add('input-has-value');
myForm.classList.add('input-has-value');
}
else{
label.classList.remove('input-has-value');
myForm.classList.remove('input-has-value');
}
}
You can listen to the 'input' event of the input element and use .closest(<selector>) to add or remove the class
$('input').on('input', function () {
if (!this.value) {
$(this).closest('form').removeClass('has-value');
} else {
$(this).closest('form').addClass('has-value');
}
})
Edit: https://codepen.io/KlumperN/pen/xxVxdzy

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

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

Function called at the start of page loading - javascript

I have a problem; for some reason, my function is being called at the start of the webapplication while the page is loading.
My code is as follows
function validateName(element) {
var len = element.value.length;
//checks if the code is than 6 characters
if (len == 0) {
element.style.backgroundColor="red";
if (element.id == "firstname")
{
document.getElementById('firstNameError').style.display = "block";
}
else if (element.id == "lastname") {
document.getElementById('lastNameError').style.display = "block";
}
return true;
} //if == 0
else {
element.style.backgroundColor="green";
if (element.id == "firstname")
{
document.getElementById('firstNameError').style.display = "none";
}
else if (element.id == "lastname") {
document.getElementById('lastNameError').style.display = "none";
}
return false;
} // if != 0
}
The logic of this function is to validate the text boxes where the user enters their name. Basically,the problem i am facing is as soon as I open up my web page, the text boxes are red, and say 'Your first name cannot be blank!' (which is the firstNameError). Then, once I enter the text in my text box, it doesn't change, it still stays red, and displays the error.
This is how i am calling the function:
function init() {
var firstName = initToolTip("firstname", "firstnameTip");
var lastName = initToolTip("lastname", "lastnameTip");
var promoCode = initToolTip("promocode", "promocodeTip");
//opens the TOS window when you click 'terms and conditions' link
document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
//checks the length of the promo code
promoCode.onblur = validatePromoCode(promoCode);
//checks the validity of a name (is not blank)
firstName.onblur = validateName(firstName);
lastName.onblur = validateName(lastName);
//document.getElementById('submitButton').onmousedown = validateForm();
}
I don't understand why it's being called as soon as the page loads, since it's set, to be called onblur.
can anyone suggest ways to fix this?
You need to pass function references to onblur, not the result of immediately calling a function. Change to this:
function init() {
var firstName = initToolTip("firstname", "firstnameTip");
var lastName = initToolTip("lastname", "lastnameTip");
var promoCode = initToolTip("promocode", "promocodeTip");
//opens the TOS window when you click 'terms and conditions' link
document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
//checks the length of the promo code
promoCode.onblur = function() {validatePromoCode(promoCode);};
//checks the validity of a name (is not blank)
firstName.onblur = function() {validateName(firstName);};
lastName.onblur = function() {validateName(lastName);{;
//document.getElementById('submitButton').onmousedown = validateForm();
}
This changes each onblur assignment to take an anonymous function reference that will be executed later when the onblur event happens, not immediately like your current code was doing.
You're not passing the function to onblur in init; you are passing the result of the function.
See the following example:
var Afuntion=function(){
console.log("hello from function");
return 22;
}
Element.onblur=Afunction("something");//Element.onblur is now 22 and
// "hello from function" is logged
Element.onblur=Afunction; //now onblur has a reference to the function
Element.onblur();//this will log "hello from function" and return 22
Youre not using a library like jQuery to make attaching/adding event listeners easy so it's a bit of a pain to set the event listener using pure JS and read the event in the function. There must be some info on SO how to do this already anyway
In your case you could try this:
promoCode.onblur = function(){ validatePromoCode.call(promoCode,promCode);};

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