Javascript Form creation is auto calling submit function - javascript

I dynamically create a form, but Func() is being called on page load, instead of on click
var addrow_f = document.createElement("form");
addrow_f.setAttribute('method',"post");
addrow_f.setAttribute('action',Func());
var submitelement = document.createElement('input');
submitelement.setAttribute("type", "submit");
submitelement.setAttribute("name", "dsubmit");
submitelement.setAttribute("value", "Submit");
AddChild(addrow_f, submitelement);
AddChild(addrow_masterContainer, addrow_f);

The action attribute just indicates to what target the form request shall be send to.
And: Since you pass the parameter with parenthesis () it will be executed immediately. If you want to pass functions as callbacks, you have to do this without parenthesis.
If you want to react on events, you have to add event listener like click on an element. So you probably want to add an click event on the submit button.
Therefore it exists a function called addEventListener available for elements. You can use it like this: submitelement.addEventListener("click", Func);

Related

JavaScript: Add Event Listeners to Dynamic Form Where Specific Form Elements Don't Exist on Page Load?

I'm curious if there is a way to add event listeners to form fields which are dynamic and not present at page load? My issue is I'm working with a form which is dynamic and changes based on selections made. The issue is, I need to attach event listeners to specific fields in the form but on page load, not all these form elements exist? For example, the dropdown below will always exist on the page:
`var employmentStatusSelect = document.getElementById('mainForm:cont_appRequestStatus');
employmentStatusSelect.addEventListener('change',trackEmploymentStatusSelect);`
but the next field will show if there is a specific selection from above element
var startCurrentJobInput = document.getElementById('mainForm:cont_appRequeststart_job');
startCurrentJobInput.addEventListener('blur', trackStartCurrentJobInput);
Since it doesn't exist when the page loads, I can't attach an event listener to it and the above code throws an error. Is there any way to attach the event listener to the 2nd element once it appears? JavaScript only, please! * I cannot make changes to the form or page and can only inject my code via a Tag Management system *
Update a better way. Turn out if you add a blur event listener to form, all input element will trigger that event too. https://developer.mozilla.org/en-US/docs/Web/Events/blur
var form = document.getElementById('mainForm');
form.addEventListener('blur', function( event ) {
if(event.target.matches('#cont_appRequeststart_job')){
console.log('blur event triggered');
}
}, true);
// add input
var input = document.createElement('input');
input.id = 'cont_appRequeststart_job';
form.appendChild(input)
<form id="mainForm">
</form>
You can keep trying every 0.5s until the element exists. Not recommended.
function tryBindEvent(){
var startCurrentJobInput = document.getElementById('mainForm:cont_appRequeststart_job');
if(startCurrentJobInput){
startCurrentJobInput.addEventListener('blur', trackStartCurrentJobInput);
}else{
setTimeout(tryBindEvent, 500);
}
}
tryBindEvent();
You can attach a event listener on the document body and check the element type inside the callback and do the modifications.
document.addEventListener('change', function(e) {
if(e.target && e.target.id === 'mainForm:cont_appRequeststart_job') {
//do something
}
});
First of all, if you share more codes, you may get better help. But, I guess what you should do is to run a function (I will call it assign() for now) to assign a value to startCurrentJobInput when employmentStatusSelect has a value.
So, I recommend you to define startCurrentJobInput variable globally like this (I guess you would need it globally to use in other funcs):
var startCurrentJobInput;
And do not add event listener yet. Then, when employmentStatusSelect is selected and new form element created, run assign func to assign document.getElementById('mainForm:cont_appRequeststart_job') to startCurrentJobInput. Then, you can add event listener to it with:
startCurrentJobInput.addEventListener('blur', trackStartCurrentJobInput);

Update button onClick url from AJAX in Laravel

I have a simple form with a "Submit" button and an additional "Add" button in blade template. On form submit there is an ajax callback to a controller which validates provided value. Based on the returned result from the controller, I'd like to change the "Add" button onClick event. Here is blade snip:
<button id="theId" type="button" >Add</button>
Relevant ajax pice:
$.ajax({
...
success: function(result){
//Update onClick for the add button
addButton.onclick=function () {
//location.href = 'www.example.com';
window.location="www.example.com";
};
addButton.html("aNewName");
}
}
Based on all the sources either location.href or window.location should redirect me to a different page (in my case just a different subpage) but it does not. After hours of research I thought that I get a wrong button or sth is wrong with the ajax itself but then I added addButton.html line and this works well. What do I do wrong here?
Get the button, remove eventually previous click events, add the new event using the http/https prefix, change the text of the button
success: function(result){
var button = document.querySelector('#theId');
button.addEventListener('click', function () {
window.location = 'https://www.google.it';
});
button.innerHTML = "my new button text";
}
From the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers#Registering_on-event_handlers, a handler registered via an on* attribute will be available via the corresponding on* property, but not the other way around.
What this means is that the onclick attribute of the div remains the old event handler in HTML.
To keep sanity, always register event listeners with the addEventListener method.
It looks like you are trying to set a jQuery object's onclick property to a function, which is not the right way to set a click event handler in jQuery.
You should use the jQuery object's click method to set a click handler. And use the off method to remove the previous handler:
addButton.off('click');
addButton.click(function () {
window.location="https://www.example.com";
})
Here's a working fiddle.

Automatic onsubmit handler in loop

I have the following problem with Javascript.
I'm trying to add an "onsubmit" handler automatically (after the page has been loaded) to every form element in the page.
So I wrote this script:
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=function(param){
return formValidator(param);
}(formElements[k]);
}
};
The formValidator function takes a form object as parameter, validates the content of the input and textarea elements inside the form and returns true or false as results of the validation.
In the HTML file of the page I have a form element without the onsubmit attribute (that should be inserted by javascript).
The problem is that it seems that the form is automatically validated when the page is loaded (even if the user doesn't submit the form). And then if the user starts to insert data in the form and clicks the submit button the validateForm function doesn't execute.
Any ideas?
Thank you.
You're calling your handler function, and assigning the result of calling it to onsubmit. (The (formElements[k]) after the function calls it.)
You need to refer to the function without calling it. One good way to do that in the general case is to use a builder function (but see below for why that general case probably doesn't apply here):
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=buildHandler(formElements[k]);
}
function buildHandler(form) {
return function(){
return formValidator(form); // <== I'm guessing `formvalidator` takes the form
};
}
};
But there's no need to create a separate handler for each form. The way you're assigning the handler, this will be the form element, so just:
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=handler;
}
function handler(){
return formValidator(this);
}
};
The thing about this being the element will be true when you assign functions to onxyz properties on DOM elements, when you use attachEvent (on IE), or when you use addEventListener (standard). It is not true if you call a function from onxyz attributes in the markup, e.g. onsubmit="foo()" (although you can use onsubmit="foo.call(this);" and it will be).

jQuery change event triggered when element is built

I'm building some dynamic select lists with jQuery. When they are changed, I want the event to trigger a function to get a data refresh.
var selector = $('<select id="myid" />');
selector.append($('<option value>Option Placeholder</value>'));
// attach onChange event to select list
selector.bind('change', doUpdate(this));
My problem is that the change event gets fired every time the select list is built. I'm not sure how the trigger is happening-- I'd expect it to only trigger the change event when it, well, changes!
http://jsfiddle.net/TPuwc/
When you do this:
selector.bind('change', doUpdate(this));
what you're expecting to happen is to bind the event handler to execute the doUpdate function, passing this as an argument.
That isn't what's happening. Instead, what it's doing is calling doUpdate(this) immediately, and then attempting to set the value returned by that function call as the event handler for the change event.
You can simply do:
selector.bind('change', doUpdate);
jQuery will handle the value of this for you (it will be the element triggering the event), so you don't need to pass it in to the function as an argument.
You'll have to understand the difference between function calls and function references. Every callback should be provided as a function reference (or an anonymous function) and not a function call.
The difference is the parentheses () after the function name.
selector.bind('change', doUpdate);
EDIT: Be sure to update the doUpdate function. It will automatically have access to the element that triggered the change using the this keyword, so you don't need to pass it as a parameter.
Your event arrachment method is wrong. for event attachment you should pass function. while here you are executing function and passing return value.
var selector = $('<select id="myid" />');
selector.append($('<option value>Option Placeholder</value>'));
// attach onChange event to select list
selector.bind('change', function(){ doUpdate(this) });

Explain this fragment of Javascript to me

I am newbie to jQuery,
can someone explain what this code does:
$("#currency form").submit(function(e) {
triggers.eq(1).overlay().close();
return e.preventDefault();
});
The first line begins a function that handles the submit event of all form tag(s) in the element with ID currency.
Documentation: Selectors, submit event
The second line closes an overlay in the second element in the triggers variable.
Documentation: eq method, overlay plugin
The third line tries to prevent the submit, but isn't completely correct. (It should be e.preventDefault(); and/or return false;)
Documentation: event.preventDefault, event handlers
triggers = a jQuery object
triggers.eq(1) = get the second element from the matched elements inside the jquery object
triggers.eq(1).overlay() = get the overlay instance (a plugin) on the second element
triggers.eq(1).overlay().close() = close the overlay.
return e.preventDefault(); = prevent the default action (form submission)
On the submit event of the form, it will:
Get the second element in the triggers collection (of jQuery elements).
Get the overlay on that element.
Close that overlay.
Prevent the submit event from bubbling to the parent handler.

Categories

Resources