Using "if" inside an "onclick - javascript

Please before posting or commenting ... read and understand that this is inside an application that generates the web page and I cannot create a function I can only edit with will happen inside the onclick
Is it possible to use a "if" function inside an "onclick".
The reason why I have to do this is because this "onclick" is used inside an application that I do not control the code, the only thing I can control is what happens inside the "onclick"
For example:
onclick="document.getElementById('REF_DOC_1_NUMBER').value = '';"
I can write the:
document.getElementById('REF_DOC_1_NUMBER').value = '';
I cannot declare any function in the webpage... cause it's an application that compiles the pages... I can only write what is written in the tag onclick...
But not a function. The page is generated by the application itself so I do not control the header.
What I need, a IF that checks an other ID and to change the value ONLY if the value of the other ID (REF_DOC_1_CHOICE) is NA (not applicable)
Any thoughts?

Yes, you can use any inline statement you want. The onclick event is a function by itself. As you can define one in JS in the header:
document.getElementById('mydiv').onclick = function() {
var a = 2;
if (a > 1) {
// do stuff
}
};
You can also do so inline:
onclick="var a=2;if(a>1){a=3}else{a=-1}"
onclick="a == 12 && b = true || b = false"
Here's a JSFiddle

though it is not a good practice to use inline javascript but you can use an if in onclick
onclick="document.getElementById('REF_DOC_1_NUMBER').value = '';if(condition){dosomething}else{dosomething else}"

You may use ternary operator. Somehow like this:
onclick="document.getElementById('REF_DOC_1_CHOICE') == 'some_value'? (document.getElementById('REF_DOC_1_NUMBER').value = '') : 0"

Define a function like this :
onclick="function(text){
// My stuffs
if(text==='test')
document.getElementById('REF_DOC_1_NUMBER').value = '';
}";

Related

Onclick button running automatically after $() insertion

I'm 99% through done writing this code but I'm stuck on the last hurdle.
The main issue here is:
I have 2 HTML buttons which aim to change text based on the function output, successful or not.
Currently, the logic for the functions is working - ie the expected returned values are as expected.
However, when I try to move these functions into my HTML file, they automatically run, which is overwriting the default value and defeating the point of having the button.
Button:
<button id="goldButton" onclick = "${calcGoldTierStatus(exampleCustomer)}">Click me!</button>
<h2 id="goldResult">Gold tier eligibility:${goldTierEligible}</h2>
Function earlier in same script.js:
function calcSilverTierStatus() {
if (
exampleCustomer.previousStays >= silverTier.previousStays &&
exampleCustomer.bookingAgencyId === null || String || Number &&
(exampleCustomer.roomSpend / (exampleCustomer.roomSpend.length+=1)) >= 100 &&
exampleCustomer.reservationNights >= silverTier.previousStays
) {
silverTierEligible = ("Silver Eligibility:Eligible for Silver tier!")
} else {
silverTierEligible= ("Silver Eligibility:Not eligible for Silver Tier")
}
}
What may be noteworthy is that I am passing the values into HTML via declaring a const 'content', then using:
document.body.innerHTML = content;
to write the HTML body.
It seems to be the $(calcGoldTierStatus(exampleCustomer)} that is causing the autorun, but I had no idea how to otherwise move the function into HTML from JS.
I found from some posts that it is bad practice to use template literals inside onclick buttons. Instead, using a combination of event listeners, getElementById, and appending a HTML article object instead of replacing main, solved most my problems.
#me for a look at the exact ways I got around this.

Boolean Variables in Javascript

I am trying to set up a simple boolean variable in js in order to control a few things however I am having some issues relating to when it is being fired. The boolean variable is changed whenever the user clicks a button which runs the function changeVariable(). The issue is that the alerts are firing on page load and not when the user clicks a button which runs the specified function. If anyone could take a look, that would be much appreciated.
Code is here:
var triggered = false;
function changeVariable() {
triggered = ! triggered;
}
if (triggered = true) {
alert(triggered);
}
if(triggered = false) {
alert(triggered);
}
triggered = true it is an assignment. Use == or ===.
=== it checks for type also.
The issue is that the alerts are firing on page load and not when the user clicks a button which runs the specified function.
That's because the code which performs the test and does the alert is not inside the function. Move it.
Aside: = is an assignment, to perform a comparison use == or ===. For boolean tests, consider a simple if (value) instead. Also consider the use of else instead of duplicating a test with a negative modifier.

How can I use onclick method?

I made object of window by javascript. And I want to add some functions to the windows object. But .onclick, .setattribute, and .addEventListener do not work with my object. Even mouse cursor also can not be changed when I give value of css or javascript. It is on 499 line of my source. Could you tell me why these do not work? Should I change language? Is it bug?
function seSizeValue(theNumOfWins,outlayerId){
var seSizeValue;
var seSizeValueId;
seSizeValueId = "seSizeValueId" + theNumOfWins;
seSizeValue = document.createElement("div");
document.getElementById(outlayerId).appendChild(seSizeValue);
seSizeValue.setAttribute("id",seSizeValueId);
document.getElementById(seSizeValueId).setAttribute("class","seSizeValueCSS");
document.getElementById(seSizeValueId).onclick = function(event) {seSizeChange();};
return seSizeValueId;
}
"""document.getElementById(seSizeValueId).onclick = function(event) {seSizeChange();};"""
This line does not work. I already tried to change '.setattribute', and '.addEventListener'.
There was no error. But it does not work.
https://drive.google.com/file/d/0B4p8lZSEMXcqN0FzQTkyVW8wRGc/view
this is my full source.
It does not work on my source.
Should I use jQuery?
I think so Save the window reference in a variable with a sentence like that
var new_window = window.open
is posible ser manually events in DOM subelements using jquery with On() method o directly with javascript.
Im not sure about that but I suggest a posible solution.
There is no function defined as "seSizeChange" so when the onclick event fires, it's going to run a function that doesn't exist.
Also, when you call this "seSizeValue" function, are you calling it after the specified element has been loaded on to the document?
If not, the code won't be able to find the specified element.
document.getElementById(seSizeValueId).onclick = function(event) {seSizeChange();};
is definitely wrong.
See http://jsfiddle.net/2txugfq5/
Everything is working except fact that 'seSizeChange' is not defined.
John makes good points.
See here http://jsfiddle.net/hqw7ocwj/2/ , works fine. No changes to anything of importance from your code, apart from:
$(document).ready(function() {});
and:
function seSizeChange() {
alert("seSizeChange method fired.");
}
Main points:
1. Ensure your JavaScript is called only after the DOM is ready: $(document).ready(function{});
2. Make sure that the method in the function that the onclick refers to has been defined.

How can I add a link to dynamically created button?

Once the buttons are created, is there anyway I can add a link or use window.location method like this: `window.location = 'nextpage.html?foo=number'. I currently have this
var typeValue = location.search;
var typeStringValue= typeValue.replace("?type=","");
var containers = typeValue.replace("?type=multi","");
var containersValue = parseInt(containers);
var sampleLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function createButton(buttonName){
var buttonDivBlock = document.getElementById("sampleSets");
var buttonElement = document.createElement("input");
buttonElement.setAttribute("type","button");
buttonElement.setAttribute("name",buttonName);
buttonElement.setAttribute("value","Sample Set"+" "+buttonName);
buttonElement.setAttribute("id",buttonName);
buttonDivBlock.appendChild(buttonElement);
// document.getElementById(sampleLetter[i]).setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
}
function setButtons(numberOfContainers){
for(i=0;i<numberOfContainers;i++){
createButton(sampleLetter[i]);
}
}
window.onload = function(){
setButtons(containersValue);
}
But document.getElementById("'"+sampleLetter[i]+"'").setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
returns a null value.
Well, maybe I can help you along with an example:
function getFive() { return 5;}
callOtherFunction("stringArgument", getFive());
The second argument to callOtherFunction is going to be 5, not the getFive function. In many cases, like adding event listeners and AJAX code, you actually want to pass the function itself as an argument, so it can be called later. But if you don't want to bother declaring that function seperately, it looks like this:
callOtherFunction("stringArgument", function() { return 5; });
To make code look cleaner, you can press Enter after the { and make a multi-line function.
Now, all that in mind, take another look at the line you've commented out. Do you see what's missing? (PS. Apologies for the "egging-on" format - I find people get much better at figuring things out if I help them find the solution, rather than just showing it to them)
The sampleLetter variable is not defined where you are trying to use it (judging by commented code). Use the value you had just set to the id attribute a few lines earlier.
document.getElementById(buttonName).setAttribute( /* ... */ );
Or if you are trying to set it in the loop instead of in the createButton function, do not add the single quotes
document.getElementById(sampleLetter[i]).setAttribute( /* ... */ );

Get selected time in javascript control

I'm using the following JavaScript Control:
http://www.ama3.com/anytime/
How do I get the selected date in the control? So I can pass it to a postback page?
I tried finding it, but I'm just not very good at JavaScript :(
Which function do I have to call?
// Initialization
$(document).ready(function () {
//alert("welcome");
$("#DateTimeDemo").AnyTime_picker(
{ format: "%Y-%m-%d %H:%i: %E",
formatUtcOffset: "%: (%#)",
hideInput: true,
placement: "inline"
});
// Asp.net code
<input type="text" id="DateTimeDemo" style="background-color:Green;" />
I assume the code will be something like this:
var x = getBlaBla();
Where x is something that I can use to pass to C# for postback info. I think I'll have to use JQuery to select the object I'll be taking the date out of.
Edit:
Okay I think I have to use something like this:
$("#DateTimeDemo").AnyTime_current(g, k);
what do the g and the k stand for? What do I have to pass?
As Joe Johnson earlier commented, you will likely want to attach an event handler. With this method, whenever your input changes within the DateTimeDemo field, you can do something with that value.
$(function() {
$("#DateTimeDemo").change(function() {
var dt = $("#DateTimeDemo").val();
alert(dt);
// do something with dt.
});
});
I think I'll have to use JQuery to select the object
You never "have" to use jQuery, or any library. You can add an in–line listener like:
<select ... onchange="someFunc(this.value);" ...>
Where the logic for adding the listener is on the server, so no different to adding it at the client (but faster and more robust than any client–side method).
Or add it as a DOM property sometime after the element is created in the document (use the load event or a script at the bottom of the page):
document.getElementById('selectID').onchange = function(){someFunc(this.value);};
Or use addEventListener:
document.getElementById('selectID').addEventListener('change', function(){...}, false);
but include support for other browsers too (e.g. an addEvent function).

Categories

Resources