Is there a way to show an alert if you try to set the variable to the same value?
Example:
<h1 id="t_example" onclick="examplefunction()"></h1>
JavaScript
var example = "example"
function examplefunction(){
example = "example2"
}
And now if the user clicks again I want to show the alert saying that the user can't click it again, because it has the same value.
if (example == "example2"){
alert() // You have inserted the same value
}
You can do like this: First check if is same or not. If it is the same alert, the text is not replacing the variable.
var example = "example"
function examplefunction() {
if (example == "example2"){
alert('same value')
}
else {
example = "example2"
}
console.log(example)
}
console.log(example)
<h1 id="t_example" onclick="examplefunction()">check</h1>
function examplefunction(){
if(example !=="example2" ){
example = "example2"
}
else{
alert("Please dont click again")
}
}
For checking multiple items clicks:
var clickArr = [];
function examplefunction(value){
if (clickArr.indexOf(value) != -1) { // If already clicked
alert("Already clicked");
} else { // Save in the array if clicked for the first time
clickArr.push(value);
}
}
<h1 id="t_example1" onclick="examplefunction('example1')">click1</h1>
<h1 id="t_example2" onclick="examplefunction('example2')">click2</h1>
Related
I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});
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
On change of a dropdown value, I need to confirm whether the user wants to change the value or changed it by mistake.
If user clicks on OK then system should apply the modification, otherwise the value should not change.
As of now I have written code as follows:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
return this;
}
}
here am getting the confirm box but regardless of whether if I press OK or Cancel, the dropdown always shows the new value.
check this fiddle
var drop = document.getElementById("dropdownid");
var selected =drop.options[drop.selectedIndex]; //save selection initially
drop.onclick = function (e){
selected = drop.options[drop.selectedIndex]; // save current selection
}
drop.onchange = function (e){
var a = confirm("Do you want to change");
if (a == false) // no need to check for true
{
selected.selected=true; // if cancel, set the existing selected option
}
}
Please try this:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true)
{
return true;
}
if (a == false)
{
return false;
}
}
You can undo the selection like this:
document.getElementById("dropdownid").onchange = function (){
if (!confirm("Do you want to change")) {
if (typeof this.prevVal=='undefined') {
this.prevVal=this.options[0].value;
for (var i=0;i<this.options.length;i++)
if (this.options[i].defaultSelected)
this.prevVal=this.options[i].value;
}
this.value=this.prevVal;
} else {
this.prevVal=this.value;
}
}
Basically you save in an attribute the previously selected value, and you search for the default value if not changed yet.
try using this code
document.getElementById("dropdownid").onchange = function (eve){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
eve.preventDefault();
}
}
I want to check a textarea whether it is empty or not. For this I write the following code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
For the first time it is working fine. But If I remove the text from the textarea the above function is returning true value i.e., it is assuming the previous text I've entered into the textbox. Can anybody kindly tell me where is the problem?
I am getting it correctly. This is what I did.
Click on validate, it said Please Write Problem Description.
Write something and click. Nothing happened.
Remove the text. Click on validate, it said Please Write Problem Description.
Note: Use a trim function to eliminate empty spaces.
Code:
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if ($.trim(problem_desc.value) == '') {
alert("Please Write Problem Description");
return false;
} else {
return true;
}
}
Demo: http://jsfiddle.net/TZGPM/1/ (Checks for Whitespaces too!)
Do check for white space in the value like this
if (problem_desc.value.match (/\S/)) { ... }
or other way check for length
problem_desc.value.length == 0;
Remove spaces and calculate length of the value attribute.
function validateForm(theForm) {
var problem_desc = document.getElementById("problem_desc");
if (problem_desc.value.replace(/ /g,'').length) {
return true;
} else {
alert("Please Write Problem Description");
return false;
}
}
<textarea id="problem_desc"></textarea>
<button onclick="validateForm()">Validate</button>
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/