Is there a way to capture the id of the dom element in a variable? - html

I have an element in "this" how do i get its id's value (and class's value)?
alert(this.id) ;
returns undefined.

First of all you should check if this is really your target element and not global window object. Let me illustrate my advice:
function foo() {
if (this === window) {
alert("'this' is actually 'window'");
} else {
alert("'this' is not 'window'");
}
}
foo(); // will alert: 'this' is actually 'window'
but:
document.onclick = foo;
// every mouse click will produce alert: 'this' is not 'window'
Anyway, I'd suggest you to use Firebug/Chrome console to inspect the real value of this object:
console.log(this); // will reveal you the real nature of _this_ ;-)

Probable duplicate for this.
You need to send the ID as the function parameters. Do it like this:
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
This will send the ID this.id as clicked_id which you can use in your function. See it in action here.

Related

jQuery get content of textarea

I would like to get the content of my textarea when onkeyup event triggered.
I tried this:
<textarea onkeyup="getContent(this)"></textarea>
function getContent(txtBeschreibung) {
console.log(
txtBeschreibung.val()
)
}
but my output is this:
TypeError: txtBeschreibung.val is not a function. (In 'txtBeschreibung.val()', 'txtBeschreibung.val' is undefined)
Where is my mistake? :/
I was able to get your code to run with minor modifications
function getContent(txtBeschreibung) {
let val = $(txtBeschreibung).val();
console.log(val);
}
It looks like you need to wrap the reference (this) in a dollar-sign to perform jQuery operations on it.
txtBeschreibung isn't a jQuery object, to use jQuery, you could do this
function getContent(txtBeschreibung) {
console.log($(txtBeschreibung).val());
}
or in Vanilla JS:
function getContent(txtBeschreibung) {
console.log(txtBeschreibung.value);
}

How do I create the onClick function for a button with Kotlinx.html?

I am using Kotlin's html library kotlinx.html for dynamic html building.
I want to create a button which triggers a function when clicked. This is my current code:
class TempStackOverflow(): Template<FlowContent> {
var counter: Int = 1
override fun FlowContent.apply() {
div {
button(type = ButtonType.button) {
onClick = "${clicked()}"
}
}
}
fun clicked() {
counter++
}
}
This results in the following source code:
<button type="button" onclick="kotlin.Unit">testkotlin.Unit</button>
Which gives this error when clicked (from Chrome developer console):
Uncaught ReferenceError: kotlin is not defined at HTMLButtonElement.onclick
I have tried several approves, and search for a solution - but could not find the proper documentation.
I am not a Kotlin expert, but it's perfectly possible to write event handlers using kotlinx. Rather than:
onClick = "${clicked()}"
have you tried using this?
onClickFunction = { clicked() }
If you really need a bit on Javascript here, you can type this:
unsafe {
+"<button onClick = console.log('!')>Test</button>"
}
Good for debugging and tests, but not very nice for production code.
Unfortunately, you're completely missing the point of the kotlinx.html library. It can only render HTML for you, it's not supposed to be dynamic kotlin->js bridge, like Vaadin or GWT. So, you just set result of clicked function converted to String to onClick button's property, which is effective kotlin.Unit, because kotlin.Unit is default return value of a function if you not specify another type directly.
fun clicked() {
counter++
}
is the same as
fun clicked():Unit {
counter++
}
and same as
fun clicked():Kotlin.Unit {
counter++
}
So, when you set "${clicked()}" to some property it actually exec function (your counter is incremented here) and return Koltin.Unit value, which is becomes "Kotlin.Unit" string when it rendered inside "${}" template

pass a local variable to an click function

I want to pass a local variable from one function to another and I have tried some solutions but they didn't work because I have a click function, I need to put the variable first of all and I don't how to do it, also I declared the variable outside the function but if I use it outside of all the functions it doesn't has all its values or inside the function resaltar nothing appears, any help is welcome
let children=$('div[class^="fila"], div[class^="pieceRow"]' ).children()
var clase
$(children).each(function getClass(){
clase=$(this).attr('class')
$(clase).on('click', function resaltar(){
if (clase==clase) {
$(this).addClass('shadow')
}
})
})
this is the html code https://jsfiddle.net/qb5fwcus/
Please try this code :
let children = $('div[class^="fila"], div[class^="pieceRow"]' ).children();
$(children).on('click', function(){
var clase = $(this).attr('class');
resaltar(clase);
})
function resaltar(clase){
$('.shadow').removeClass('shadow');
$('.' + clase).addClass('shadow');
}
Explanation : You can not pass any value for the callback function for any event handler. Either it can be an anonymous function, or a function, not requiring any argument. However, you can achieve that, by making the callback function anonymous, and call any function from it. In this way, you can pass variables.
PS : Let me know if I got it wrong in any manner :)
Let's assume that you will be passing it to a pure JS function.
function myFunc() {
console.log("My function!");
}
In your 'click', you're calling the function ''resalter'', that you're also defining on the spot.
You want to call myFunc, so:
$(clase).on('click', myFunc())
Now, myFunc is not expecting a variable. Let's just pass a variable:
function myFunc(myVar) {
console.log("Passing a variable of type: " + typeof myVar);
}
Now, you're only expected to pass this var in the function you're calling. Given the previous example I gave, we have:
let x = 1; // our variable
$(clase).on('click', myFunc(x))
This way you're passing 'x' as a variable, of type integer. Use this code as inspiration to try and reach your goal. It is a bit hard to give a more exact answer, given that we don't know what variables have to be passed to what function and what the purpose is.
Good luck!

How to send a single request through p:commandButton inside p:dialog? [duplicate]

I have following jQuery code to prevent double clicking a button. It works fine. I am using Page_ClientValidate() to ensure that the double click is prevented only if the page is valid. [If there are validation errors the flag should not be set as there is no postback to server started]
Is there a better method to prevent the second click on the button before the page loads back?
Can we set the flag isOperationInProgress = yesIndicator only if the page is causing a postback to server? Is there a suitable event for it that will be called before the user can click on the button for the second time?
Note: I am looking for a solution that won't require any new API
Note: This question is not a duplicate. Here I am trying to avoid the use of Page_ClientValidate(). Also I am looking for an event where I can move the code so that I need not use Page_ClientValidate()
Note: No ajax involved in my scenario. The ASP.Net form will be submitted to server synchronously. The button click event in javascript is only for preventing double click. The form submission is synchronous using ASP.Net.
Present Code
$(document).ready(function () {
var noIndicator = 'No';
var yesIndicator = 'Yes';
var isOperationInProgress = 'No';
$('.applicationButton').click(function (e) {
// Prevent button from double click
var isPageValid = Page_ClientValidate();
if (isPageValid) {
if (isOperationInProgress == noIndicator) {
isOperationInProgress = yesIndicator;
} else {
e.preventDefault();
}
}
});
});
References:
Validator causes improper behavior for double click check
Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)
Note by #Peter Ivan in the above references:
calling Page_ClientValidate() repeatedly may cause the page to be too obtrusive (multiple alerts etc.).
I found this solution that is simple and worked for me:
<form ...>
<input ...>
<button ... onclick="this.disabled=true;this.value='Submitting...'; this.form.submit();">
</form>
This solution was found in:
Original solution
JS provides an easy solution by using the event properties:
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){//activate on first click only to avoid hiding again on multiple clicks
// code here. // It will execute only once on multiple clicks
}
});
disable the button on click, enable it after the operation completes
$(document).ready(function () {
$("#btn").on("click", function() {
$(this).attr("disabled", "disabled");
doWork(); //this method contains your logic
});
});
function doWork() {
alert("doing work");
//actually this function will do something and when processing is done the button is enabled by removing the 'disabled' attribute
//I use setTimeout so you can see the button can only be clicked once, and can't be clicked again while work is being done
setTimeout('$("#btn").removeAttr("disabled")', 1500);
}
working example
I modified the solution by #Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
Disable pointer events in the first line of your callback, and then resume them on the last line.
element.on('click', function() {
element.css('pointer-events', 'none');
//do all of your stuff
element.css('pointer-events', 'auto');
};
After hours of searching i fixed it in this way:
old_timestamp = null;
$('#productivity_table').on('click', function(event) {
// code executed at first load
// not working if you press too many clicks, it waits 1 second
if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
{
// write the code / slide / fade / whatever
old_timestamp = event.timeStamp;
}
});
you can use jQuery's [one][1] :
.one( events [, data ], handler ) Returns: jQuery
Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
see examples:
using jQuery: https://codepen.io/loicjaouen/pen/RwweLVx
// add an even listener that will run only once
$("#click_here_button").one("click", once_callback);
using count,
clickcount++;
if (clickcount == 1) {}
After coming back again clickcount set to zero.
May be this will help and give the desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
<p>Hello</p>
We can use on and off click for preventing Multiple clicks. i tried it to my application and it's working as expected.
$(document).ready(function () {
$("#disable").on('click', function () {
$(this).off('click');
// enter code here
});
})
This should work for you:
$(document).ready(function () {
$('.applicationButton').click(function (e) {
var btn = $(this),
isPageValid = Page_ClientValidate(); // cache state of page validation
if (!isPageValid) {
// page isn't valid, block form submission
e.preventDefault();
}
// disable the button only if the page is valid.
// when the postback returns, the button will be re-enabled by default
btn.prop('disabled', isPageValid);
return isPageValid;
});
});
Please note that you should also take steps server-side to prevent double-posts as not every visitor to your site will be polite enough to visit it with a browser (let alone a JavaScript-enabled browser).
The absolute best way I've found is to immediately disable the button when clicked:
$('#myButton').click(function() {
$('#myButton').prop('disabled', true);
});
And re-enable it when needed, for example:
validation failed
error while processing the form data by the server, then after an error response using jQuery
Another way to avoid a quick double-click is to use the native JavaScript function ondblclick, but in this case it doesn't work if the submit form works through jQuery.
One way you do this is set a counter and if number exceeds the certain number return false.
easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.
First set add a style to your button:
<h:commandButton id="SaveBtn" value="Save"
styleClass="hideOnClick"
actionListener="#{someBean.saveAction()}"/>
Then make it hide when clicked.
$(document).ready(function() {
$(".hideOnClick").click(function(e) {
$(e.toElement).hide();
});
});
Just copy paste this code in your script and edit #button1 with your button id and it will resolve your issue.
<script type="text/javascript">
$(document).ready(function(){
$("#button1").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script
Plain JavaScript:
Set an attribute to the element being interacted
Remove the attribute after a timeout
If the element has the attribute, do nothing
const throttleInput = document.querySelector('button');
throttleInput.onclick = function() {
if (!throttleInput.hasAttribute('data-prevent-double-click')) {
throttleInput.setAttribute('data-prevent-double-click', true);
throttleInput.setAttribute('disabled', true);
document.body.append("Foo!");
}
setTimeout(function() {
throttleInput.removeAttribute('disabled');
throttleInput.removeAttribute('data-prevent-double-click');
}, 3000);
}
<button>Click to add "Foo"!</button>
We also set the button to .disabled=true. I added the HTML Command input with type hidden to identify if the transaction has been added by the Computer Server to the Database.
Example HTML and PHP Commands:
<button onclick="myAddFunction(<?php echo $value['patient_id'];?>)" id="addButtonId">ADD</button>
<input type="hidden" id="hasPatientInListParam" value="<?php echo $hasPatientInListParamValue;?>">
Example Javascript Command:
function myAddFunction(patientId) {
document.getElementById("addButtonId").disabled=true;
var hasPatientInList = document.getElementById("hasPatientInListParam").value;
if (hasPatientInList) {
alert("Only one (1) patient in each List.");
return;
}
window.location.href = "webAddress/addTransaction/"+patientId; //reloads page
}
After reloading the page, the computer auto-sets the button to .disabled=false. At present, these actions prevent the multiple clicks problem in our case.
I hope these help you too.
Thank you.
One way I found that works is using bootstrap css to display a modal window with a spinner on it. This way nothing in the background can be clicked. Just need to make sure that you hide the modal window again after your long process completes.
so I found a simple solution, hope this helps.
all I had to do was create a counter = 0, and make the function that runs when clicked only runnable if the counter is = 0, when someone clicks the function the first line in the function sets counter = 1 and this will prevent the user from running the function multiple times when the function is done the last line of the code inside the function sets counter to 0 again
you could use a structure like this, it will execute just once:
document.getElementById('buttonID').addEventListener('click', () => {
...Do things...
},{once:true});

How to disable href after one click

I wish to disable a href after clicking it once.
I have the following href:
<a href="BeginPayment.aspx?PayPal=true" id ="link" onclick="javascript:clickAndDisable();">
I have added the onclick event that gets called on click.
I have attempted to change the href to be a blank path so that it cannot be clicked a second time: This is via a Javascript function.
function clickAndDisable(link)
{
alert("Entered clickAndDisable function");
this.href="''";
}
My code is all within an xslt file.
Where am i going wrong with this?
Here is my updated code following peoples suggestions:
<a href="BeginPayment.aspx?PayPal=true" id ="link" onclick="javascript:clickAndDisable(this);">
<script type="text/javascript">
function clickAndDisable(link)
{
alert("Entered clickAndDisable function");
link.href="";
}
This disables the link from working at all, I wish for the link to work the first time it is clicked, but not work any other time it is clicked.....
You can use the Javascript like
function clickAndDisable(link) {
link.onclick = function(event) {
event.preventDefault();
}
}
<a href="BeginPayment.aspx?PayPal=true" id ="link" onclick="javascript:clickAndDisable(this);">
If you can use jQuery then you can append a class on the first click and then preventDefault after that.
$('a').on("click", function (e) {
if($('a').hasClass('clicked'){
e.preventDefault();
} else {
$('a').addClass('clicked');
}
});
This Fiddle shows an example
EDIT: As pointed out by Johannes H. jQuery is not required, this can be done in pure JS as seen here
First of all: .href="''" will not set the href attribute to an empty value, but to the string ''. Instead, .href="" does what you tried.
Second: this refers to the source element of the event within the inline onclick handler. However, when a function is called in the event handler, there is no special treatment for this, so any reference to this inside the function will point to the window object.
To solve this you can either:
1) pass the element to your function:
<a href="BeginPayment.aspx?PayPal=true" id ="link" onclick="javascript:clickAndDisable(this);">
function clickAndDisable(link)
{
alert("Entered clickAndDisable function");
link.href="";
}
2) use Function.prototype.call()
<a href="BeginPayment.aspx?PayPal=true" id ="link" onclick="javascript:clickAndDisable.call(this);">
function clickAndDisable()
{
alert("Entered clickAndDisable function");
this.href="";
}
3) Use Javascript to attach the event handler and dump the inline handler (in this case, this will be set to the EventTarget that triggered the handler when calling handler function):
<a href="BeginPayment.aspx?PayPal=true" id ="link">
function clickAndDisable()
{
alert("Entered clickAndDisable function");
this.href="";
}
document.getElementById('link').attachEventListener('click', clickAndDisable);
Third: encorporating #SamAnderson's answer, instead of setting an empty value for href, you can also set a flag on first call and evaluate if it has been set on later calls, and if so, use Event.preventDefault() to prevent the normal action of the hyperlink form happening:
<a href="BeginPayment.aspx?PayPal=true" id ="link">
var clicked = false;
function clickAndDisable(e)
{
alert("Entered clickAndDisable function");
if (clicked)
{
e.preventDefault();
}
else
{
clicked = true;
}
}
document.getElementById('link').attachEventListener('click', clickAndDisable);
I ended up disabling the href after one click using the following javascript function:
function check(link) {
if (link.className != "visited") {
//alert("new");
link.className = "visited";
return true;
}
//alert("old");
return false;
}​​