Simple javascript to update a textbox when a button is hit? - javascript

I have a simple form that I'm playing around with and I'm trying to update a textbox value when a command button is clicked. The command button is called btnVerifyLocation and the textbox is called txtGeoLocation. I've attempted to do this in Javascript with the following:
The code I have is as follows:
<script type="text/javascript" id="testing">
$("btnVerifyLocation").click(function ()
{
$("input[name*='txtGeoLocation']").val("testing");
});
</script>
However when I click the button nothing happens.

A) You're missing a # in 'btnVerifyLocation' (I'm assuming that's its ID, otherwise if it's a class then use '.btnVerifyLocation'
B) Second, this should be in a $(document).ready(), otherwise you are trying to bind a click handler to a DOM element that hasn't yet been rendered.
Code should be as follows:
$(document).ready(function() {
$('#btnVerifyLocation').click(function(e) {
e.preventDefault(); // In case this is in a form, don't submit the form
// The * says "look for an input with a name LIKE txtGeoLocation,
// not sure if you want that or not
$('input[name*="txtGeoLocation"]').val('testing');
});
});

jQuery’s selector function uses CSS selector syntax, so to identify an object with an ID, you need to prefix the ID with a #:
$("#btnVerifyLocation").click(function () {
$("input[name*='txtGeoLocation']").val("testing");
});
Also just in case: You do have jQuery included, right?

Related

How do I connect a textbox to jquery events dynamically?

I have an application that uses jquery when editing date fields. It works on all fields that have the css class "date". I am reading some HTML code from the server into a DIV that functions as a pop up window. The HTML code includes several date fields and I want to have jquery manage those fields, too. The page has code pasted below in the head element and jquery automatically attaches to the appropriate fields. I need to add fields to jquery when the pop up appears and remove them when the pop up closes. When searching for an answer I could only find where jquery creates a textbox, but not attach to an existent textbox.
<script src="Include/jquery-latest.js" type="text/javascript"></script>
<script src="Include/jquery.maskedinput.js" type="text/javascript"></script>
<script type='text/javascript'>
$(function () {
// Define your mask (using 9 to denote any digit)
$('.phone').mask('(999)999-9999');
});
$(document).ready(function () {
$('.phone').change(function () {
var validnum = $(this).val().match(/^([01]?[0-9]|[0-9]|[0-9])[0-9]|[0-9]|[0-9]-[0-9]|[0-9]|[0-9]|[0-9]$/);
if (!validnum) {
$(this).val('').focus().css('background', '#fdd');
alert('Please enter a valid Phone Number (999)999-9999.');
} else {
$(this).css('background', 'transparent');
}
});
});
$(function () {
// Define your mask (using 9 to denote any digit)
$('.date').mask('99/99/9999');
});
$(document).ready(function () {
$('.date').change(function () {
var validnum = $(this).val().match(/^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/);
if (!validnum) {
$(this).val('').focus().css('background', '#fdd');
alert('Please enter a valid Date mm/dd/yyyy.');
} else {
$(this).css('background', 'transparent');
}
});
});
</script>
Why doesn't your solution work?
By using $('.date').change(... jQuery attaches event listeners to all elements present in the DOM the moment you execute this function. As your modal gets added in later, it won't have received a listener.
Solution: $(document).on('change', '.date', function () { ...
By using this, you attach the event listener to the document root, so every time anything in the document changes, jQuery checks, if the changed element matches the selector you've provided as the second param (in this case .date). So all elements, even those added later to the page will react to changes.
BUT: As I said, you attach a listener to the document. As jQuery uses a shadow-DOM in the background it won't cost you much performance, but if you build a big application with many of these listeners, you might run into performance issues at some point. In this case you'd better add the listeners specifically to the element you just added.
Since the mask and event functions are enclosed, I moved them to the routine that creates the pop up and that resolves the issue, causing them to be called again each time. I placed a date test textbox on the form and displayed properties. Each time there was only one jquery property present, so it appears everything was removed and rewritten each time.

How to add a class without access to HTML

I want to add an additional class to an input. I have no access to the HTML to change the code.
I tried the below. I don't really know JS, but have to get this done for work.
<script type="text/javascript">
function changeClass(){
document.getElementById("en__field_supporter_emailAddress").className += " xverify_email";
}
window.onload = function(){
document.getElementsByTagName("button").addEventListener( 'click', changeClass);
}
</script>
I want the JS to insert the "xverify_email" class into the email address input line (which has the id en__field_supporter_emailAddress and also already has a class that must remain there) so that it can call the subsequent xverify JS to work.
I'm assuming you have a set of buttons, so you want to bind the event click to every button in the page:
Array.from(document.querySelectorALl('button')).forEach(function(btn) {
btn.addEventListener('click', changeClass);
});
I recommend you to embrace the attribute classList:
function changeClass() {
document.getElementById("en__field_supporter_emailAddress").classList.add("xverify_email");
}

Running script after div added

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.
I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.
How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?
Yes, you can delegate the DOMNodeInserted event to the body.
function createDiv() {
$('<div />').addClass('test').appendTo($('body'));
}
$('body').on('DOMNodeInserted', '.test',function() {
alert('Created element .test');
})
$("button").on('click', function() {
createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>
In the example above the click on the button simulates your other script creating the div.
To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:
$('body').on('DOMNodeInserted', '#your_element',function() {
yourFunction();
// call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

How to have a function with event object and parameter

I show a page in a jQuery dialog box. The user fills in the fields and submits the form.
In the function I need to call e.preventDefault(). In the underlying code I used the RegisterStartupScript method on the submit button. I know how to do it by passing parameters:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, GetType(Page),
"Script", "OrderForm('Item.aspx?OrderNum=" & _ID & "');", True)
How can I pass an event object in registerStartupScript?
I want a function like this:
function OrderForm(e, number) {
e.preventDefault();
//do something using number;
}
The .click() method is part of a framework (in this case I'm pretty sure it's jQuery) and it accepts a predefined number of arguments. You can use (for example) a data- attribute in your button with the number and then access to it through the object this.
// html
<button data-number="3">my button</button>
// js
$('button').click(function(e){
e.preventDefault();
var number = $(this).data().number; // or $(this).data('number')
alert(number);
});
Try with this jsfiddle: https://jsfiddle.net/q3fvxk93/
the event object is in the scope $(this)
I don't know where number should come from.
So your code would look this
$('btn').click(function(e) {
e.preventDefault();
$(this).attr('id'); //the button and it's properties like attributes in this example I get the ID of the button
});

mixing my jQuery click events with existing object's onclick attribute

I'm using jQuery but dealing with markup produced from JSF pages. A lot of the elements have onclick attributes provided by the JSF code (which isn't my realm).
Example:
<div onclick="[jsf js to submit form and go to next page]">submit</div>
I'm trying to add some client side validation with jQuery. I need something like this pseudo code:
$('div').click(function(e){
if(myValidation==true){
// do nothing and let the JS in the onlick attribute do its thing
} else {
$error.show();
// somehow stop the onclick attribute JS from firing
}
})
Is there a best-practice for handling this?
One thought I had was that on page load, grab the onclick attribute's value, delete the onclick attribute from the object, then...well, that's where I get lost. I could cache the JS as text in a data- attribute, but I'm not sure how to fire that off later.
Just use eval to run onclick attribute code in your jQuery click event if you want it. You need to remove onclick attribute
<div onclick="alert('hi');">submit</div>
-
$(document).ready(function() {
var divClick = $('#theDiv').attr('onclick');
$('#theDiv').removeAttr('onclick');
});
$('#theDiv').bind('click', function(e) {
if (myValidation == true) {
// do nothing and let the JS in the onclick attribute do its thing
eval(divClick);
} else {
$error.show();
// somehow stop the onclick attribute JS from firing
e.preventDefault();
}
});
Either return false or use:
e.stopPropagation()
or
e.preventDefault()
Depending on your needs.
EDIT
You can save original event:
var originalEvent = $('div').attr("onclick");
$('div').attr("onclick", false);
$('div').click(function(e) {
if (false) {
// do nothing and let the JS in the onlick attribute do its thing
eval(originalEvent);
}
else {
alert("error");
// somehow stop the onclick attribute JS from firing
}
});
take a look at this http://jsfiddle.net/j4jsU/
Change if(false) to if(true) to see what hepens when form is valid.
I like e.stopProgation() and e.preventDefault(), but if you do not prefer that strategy, you could also manually remove the onclick() attribute and manually call the function it was using upon successful validation.
Different strokes..
Why can't you do something like:
div=document.getElementById('test');
oldClick=div.onclick;
bol=false;
div.onclick=function(){
if(bol){
oldClick();
}
else {
alert('YOU SHALL NOT RUN INLINE JAVASCRIPT');
}
}

Categories

Resources