How to read input from text on button click unobtrusively in Javascript? - javascript

How to read input from text on button click unobtrusively in Javascript? Can anyone provide a sample?
<script type="text/javascript>
window.onload = function() {
var btn = document.getElementById(
"btn"
);
btn.addEventListener("click",function() { alert("bar"); },false);
}
</script>
and in the body:
<div id="content">
<input type="text" id="percent" value="" />
<button id="btn">click</button></div>

Yes, addEventListener (with IE's attachEvent) is the most unobtrusive. To get the value of the textbox you simply use the .value property of the textbox.
<script type="text/javascript">
window.onload = function () {
var btn = document.getElementById("btn");
if (btn.addEventListener) {
btn.addEventListener("click", btnClick, false);
} else if (btn.attachEvent) {
btn.attachEvent("onclick", btnClick);
}
};
function btnClick() {
alert(document.getElementById("percent").value);
}
</script>

Related

How to call a js function when an element ID is clicked.

I have a web telemetry system that sends metadata to a server on element clicks. I'm looking to write JS that would allow for me to fire a function on click of specific elements by their ID.
I also would like to know if there is a js function i could write that would include html attributes from my telemetry system on the element when it is clicked, defined by the ID.
Change YourId with your element ID name without any symbols
document.getElementById("YourID").onclick = function(){
//do something after this line
}
JS FIDDLE
//calling function by name
document.getElementById("Button").onclick = sendToServer;
//or
document.getElementById("Button").addEventListener("click", sendToServer, false);
function sendToServer() {
//some code
console.log("the button clicked");
}
<button id='Button'>send to server</button>
document.getElementById("Button").onclick = function() {
//code
console.log("the button clicked");
};
//or
document.getElementById("Button").addEventListener("click", function() {
//code
console.log("the button clicked");
}, false);
<button id='Button'>send to server</button>
Maybe this is what you need
var btn = document.getElementById("button");
btn.addEventListener('click', function(){
var e= document.getElementById('container');
if (e.style.display == 'block' || e.style.display=='')
{
e.style.display = 'none';
}
else
{
e.style.display = 'block';
}
});
<button id="button">Button</button>
<div id="container">
<p> This is a paragraph </p>
</div>
Read more about document.getElementById() at MDN

Disabling a button in vanilla JavaScript and in jQuery

Vanilla JavaScript
In vanilla JavaScript, one can easily enable and disable a button using the following statement:
button.disabled = state;
This works both when humans try to click a button and when buttons are clicked programmatically:
var button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('world');
});
button.disabled = true;
button.click(); // No output
button.disabled = false;
button.click(); // Output : "Hello" and "world
button.disabled = true;
button.click(); // No output
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
This also works when using the MouseEvent interface:
var button = document.getElementById('myButton');
var click = new MouseEvent("click", {
"view": window
});
button.addEventListener('click', function() {
alert('world');
});
button.disabled = true;
button.dispatchEvent(click); // No output
button.disabled = false;
button.dispatchEvent(click); // Output : "Hello" and "world
button.disabled = true;
button.dispatchEvent(click); // No output
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
jQuery
I can't seem to be able to do the same with jQuery, though :
var button = $("#myButton");
button.on("click", function() {
alert("world");
});
button.prop("disabled", true);
button.click(); // Output : "world" and "Hello"
button.prop("disabled", false);
button.click(); // Output : "world" and "Hello"
button.prop("disabled", true);
button.click(); // Output : "world" and "Hello"
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
Both button.prop("disabled", true); and button.attr("disabled", true); simply change the disabled property of the button element, but neither disables the actual click event. This means that events are triggered whenever button.click(); is called, even if the button is disabled!
Additionally, "world" and "Hello" are output in the wrong order.
The simplest code I could come up with to emulate the behavior of the vanilla JavaScript versions, is this :
var button = $("#myButton");
button.on("click", function() {
alert("world");
});
button.disable = (function() {
var onclick = null;
var click = [];
return function(state) {
if(state) {
this.prop('disabled', true);
if(this.prop('onclick') !== null) {
onclick = this.prop('onclick');
this.prop('onclick', null);
}
var listeners = $._data(this.get()[0], "events");
listeners = typeof listeners === 'undefined' ? [] : listeners['click'];
if(listeners && listeners.length > 0) {
for(var i = 0; i < listeners.length; i++) {
click.push(listeners[i].handler);
}
this.off('click');
}
} else {
this.removeProp('disabled');
if(onclick !== null) {
this.prop('onclick', onclick);
onclick = null;
}
if(click.length > 0) {
this.off('click');
for(var i = 0; i < click.length; i++) {
this.on("click", click[i]);
}
click = [];
}
}
}
})();
button.disable(true);
button.click(); // No output
button.disable(false);
button.click(); // Output : "Hello" and "world
button.disable(true);
button.click(); // No output
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
That is, of course, ridiculously convoluted and "hacky" code to achieve something as simple as disabling a button.
My questions
Why is it that jQuery - unlike vanilla JS - doesn't disable the events when disabling a button?
Is this to be considered a bug or a feature in jQuery?
Is there something I'm overlooking?
Is there a simpler way to get the expected behavior in jQuery?
To achieve expected result, you can utilize .isTrigger within jQuery triggered click handler to determine if event is triggered by javascript, and not user action.
Define attribute event listener as a named function, where this can be passed to check disabled property at if condition if alert() is called, or not called.
Use .attr("disabled", "disabled") to set disabled at element, .removeAttr("disabled") to remove attribute; .attr("onclick", null) to remove event attribute onclick handler; .attr("onclick", "handleClick(true)") to reset event attribute.
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input type="button" id="myButton" value="button" onclick="handleClick(this)" />
<script>
function handleClick(el) {
if (el.disabled !== "disabled")
alert("Hello")
}
var button = $("#myButton");
button.on("click", function(e) {
console.log(e);
if (e.isTrigger !== 3 && !e.target.disabled)
alert("world");
});
button.attr("disabled", "disabled");
button.attr("onclick", null);
button.click(); // no output
setTimeout(function() {
button.removeAttr("disabled");
button.attr("onclick", "handleClick(button[0])");
button.click(); // Output : "world" and "Hello"
// click button during 9000 between `setTimeout` calls
// to call both jQuery event and event attribute
}, 1000);
setTimeout(function() {
button.attr("disabled", "disabled");
button.attr("onclick", null);
button.click(); // no output
}, 10000);
</script>
If you take a look to jquery-1.12.4.js at these lines:
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support (at least): Chrome, IE9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox<=42+
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
You will you see a different handling of events according to the delegation type:
$(document).on("click", '#btn', function() {
console.log("world");
});
$(function () {
$('#btnToggle').on('click', function(e) {
$('#btn').prop('disabled', !$('#btn').prop('disabled'));
});
$('#btnTestClick').on('click', function(e) {
$('#btn').click();
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<button id="btn">Click Me</button>
<button id="btnToggle">Enable/Disable button</button>
<button id="btnTestClick">Test Click</button>
Of course, if you attach the event like in:
$('#btn').on("click", function() {
alert("world");
});
The behaviour is different and seems strange.
Using .prop() is the right way to do it. I think the issue is in the way that you are "testing" it. See this example where the buttons are disabled/enabled correctly using the toggle button regardless of whether the handler is attached via onclick or with jquery.
window.testFunc = function(event) {
if (!$('#myButton2').prop('disabled')) {
alert("hello");
console.log("hello");
}
}
$(document).ready(function() {
var button = $("#myButton2");
button.on("click", function(event) {
if (!$(this).prop('disabled')) {
alert("world");
console.log("world");
}
});
$('#toggleButton').click(function() {
$('#myButton1').prop('disabled', !$('#myButton1').prop('disabled'));
$('#myButton2').prop('disabled', !$('#myButton2').prop('disabled'));
});
$('#tester').click(function() {
$('#myButton1').click();
$('#myButton2').click();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="myButton1" value="vanilla button (hello)" onclick="window.testFunc(event)"/>
<input type="button" id="myButton2" value="jquery button (world)"/>
<input type="button" id="toggleButton" value="toggle disabled"/>
<input type="button" id="tester" value="test the buttons"/>
The other obvious solution is to just use vanilla javascript. Just because you are using jQuery doesn't mean that everything "must" be done using it. There are some things that are fine to do without jQuery.
EDIT: I edited the snippet showing how you could prevent jquery's .click() from actually triggering the alerts.
You're calling the click function directly 3 times ( button.click() ) which fires regardless of disabled attribute.
The disabled property only responds to click events.
See the updated example:
var button = $("#myButton");
var button2 = $("#myButton2");
button.prop("disabled", false);
button.on("click", function() {
alert("world");
button2.prop("disabled", false);
});
button2.prop("disabled", true);
button2.on("click", function() {
alert("world");
button.prop("disabled", true);
});
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<input type="button" id="myButton" value="button" onClick="alert('Hello')"/>
<input type="button" id="myButton2" value="button2" />

Override a submit type button to call custom javascript method instead

I cannot alter the following code, but instead must override the default functionality of the button so that when clicked, a custom javascript method is called instead of the form being submitted.
And to accomplish this I must use javascript via injection.(Its a AIR desktop app using the twitter api)
Can anyone help?
<body>
<form><fieldset class="buttons">
<input class="submit button" id="cancel" name="cancel" type="submit" value="Cancel" />
</fieldset>
</form>
<body>
If you want to prevent form from submitting overiding click wont be enough. One can submit you form by Ctrl+Enter.
You can do the following http://jsfiddle.net/tarabyte/R5yQq/.
Find the form assuming you know button id.
function getForm(id) {
var button = document.getElementById(id);
while(button &&
(button = button.parentNode) &&
(button.nodeName !== 'FORM')){}
return button;
}
Add 'submit' event listener.
var form = getForm('cancel'),
handler = function(ev){
ev = ev || window.event;
if(ev.preventDefault) { //w3c browsers
ev.preventDefault();
}
else { //IE old
ev.returnValue = false;
}
alert('Custom logic goes here!');
};
if(form) {
if(form.addEventListener) {
form.addEventListener('submit', handler, false)
}
else if(form.attachEvent) {
form.attachEvent('onsubmit', handler);
}
}
Replace it via JS with a button that calls your function
document.getElementById('cancel').parentNode.innerHTML = '<input type="button" onClick="myFunc()" value="replaced">';
window.myFunc = function() { alert('clicked'); return false; }
http://jsfiddle.net/e37nd/

javascript button show/hide on text changed

I want to show and hide a button by using java script.
My problem is that the button should be hide on page load and when I changed the text in text box then button should be show.
thanks.....
pls, Check this page and tell if this is what you wanted.
Basically, you need to use onchange event to do whatever you want to do.
<html>
<head>
<script>
window.onload=function(){
document.getElementById("button").style.display='none';
}
function showButton(){
document.getElementById("button").style.display='block';
}
</script>
</head>
<body>
<input type="button" id="button" value="New Button"/>
Change the text in Input Box. Then Button will be show<br/><br/>
<input type="text" id="userText" value="Change the text" onchange="showButton()"/>
</body>
</html>
Try with jQuery:
$("#yourInput").bind("change", function() {
var value = $(this).val();
if (value && value.length > 0) {
// Exist text in your input
$("#yourButton").show();
} else {
$("#yourButton").hide();
}
});
For non-jQuery:
function onchangeInput() {
var value = this.value;
if (value && value.length > 0) {
// Exist text in your input
document.getElementById("yourButton").style.visibility = "visible";
} else {
document.getElementById("yourButton").style.visibility = "hidden";
}
}
window.onload = function() {
document.getElementById("yourButton").style.visibility = "hidden";
var el = document.getElementById("yourInput");
if (el.addEventListener) {
el.addEventListener("change", onchangeInput, false);
} else {
el.attachEvent('onchange', onchangeInput);
}
}
Again, don't show/hide a button, just disable it, that make the best user experience.
You could style the css to visibilty:hidden then in javascript add an event listner like this:
<script type="text/javascript">
var box = document.getElementById('box');
var textbox = document.getElementById('textbox');
textbox.addEventListener("focus",showbox,false);
function showbox() {
box.style.visibility = 'visible';
}
That would make it appear on focus but if you wanted to take it a step further you could add another event listener for a keystroke when the textbox is focused on. That would probably work.
This is to hide/show a div based on text changed in text box.
With JQuery
<script type="text/javascript">
window.onload = function () {
document.getElementById("submitdiv").style.display = 'none';
}
$(function () {
$('.Name').on('keyup change', function () {
if (this.value.length > 0) {
$('#submitdiv').show();
} else {
$('#submitdiv').hide();
}
});
});
</script>
HTML
<%:Html.TextBoxFor(m => m.FirstName, new { #class ="Name"}) %>
<div id="submitdiv">
<button type="submit" value="Submit" class="btn btn-primary pull-right value-set" id="btnLogin">Submit</button>
</div>
Try this:
<script>
function
changeButton() {
document.getElementById("changeButton").innerHTML = "Insert text for button";
document.getElementById("changeButton").removeAttribute("hidden");
}
</script>
<button hidden id="changeButton"></button>

I am trying to make a simple toggle button in javascript

I am trying to make a simple toggle button in javascript. However, the button will only turn "OFF" and will not turn back "ON"
<html><head></head>
<script type="text/javascript">
function toggle(button)
{
if(document.getElementById("1").value=="OFF"){
document.getElementById("1").value="ON";}
if(document.getElementById("1").value=="ON"){
document.getElementById("1").value="OFF";}
}
</script>
<body>
<form action="">
<input type="button" id="1" value="ON" style="color:blue"
onclick="toggle(this);">
</form></body></html>
I am running:HP Netbook : Ubuntu Linux 10.04 : Firefox for Ubuntu 1.0.
Why are you passing the button if you're going to look it up?
Also, since you know the possible values, you only need to check if it's OFF, otherwise, you know it's ON.
// Toggles the passed button from OFF to ON and vice-versa.
function toggle(button) {
if (button.value == "OFF") {
button.value = "ON";
} else {
button.value = "OFF";
}
}
If you wanna get fancy and save a couple of bytes you can use the ternary operator:
function toggle(b){b.value=(b.value=="ON")?"OFF":"ON";}
Both of your if statements are getting executed one after each other, as you change the value and then immediately read it again and change it back:
function toggle(button)
{
if(document.getElementById("1").value=="OFF"){
document.getElementById("1").value="ON";}
else if(document.getElementById("1").value=="ON"){
document.getElementById("1").value="OFF";}
}
Adding the else in there should stop this happening.
Another method to do this is:
var button = document.querySelector("button");
var body = document.querySelector("body");
var isOrange = true;
button.addEventListener("click", function() {
if(isOrange) {
body.style.background = "orange";
}else {
body.style.background = "none";
}
isOrange = !isOrange;
});
In the JavaScript file.
/*****
NOTE!
Another way is applying a class to the element that we want to change.
The CSS file must have the class with the format we want:
.orange {
background: orange;
}
By last in our js file we only need to make the application of the class:
var button = document.querySelector("button");
button.addEventListener("click", function() {
document.body.classList.toggle("orange");
});
Regards :)
Why not use a switch?
function toggle(button)
{
switch(button.value)
{
case "ON":
button.value = "OFF";
break;
case "OFF":
button.value = "ON";
break;
}
}
<html>
<head>
<script type="text/javascript">
function toggle(button)
{
if(document.getElementById("1").value=="OFF")
{
document.getElementById("1").value="ON";
}
else
{
document.getElementById("1").value="OFF";
}
}
</script>
</head>
<body>
<form action="">
<input type="button" id="1" value="ON" style="color:blue" onclick="toggle(this);">
</form>
</body>
</html>
This will resolve your issue.
let isOn = true;
function toggle(button) {
isOn = !isOn;
if (isOn) {
document.getElementById("1").value = "ON";
} else {
document.getElementById("1").value = "OFF";
}
}

Categories

Resources