Getting a form to submit from JavaScript? - javascript

I have a form in a JSP as follows:
<form action = "<c:url value = '/displayVisualisation' />"
title = "${item.visDescription}"
method = "post" onClick = "return confirmRequest('Do you want to change to
another visualisation type?');">
<input class = "text" type = "text" value = "${item.visTypeName}">
</form>
Which calls a Javascript method as follows:
function confirmRequest(questionText) {
var confirmRequest = confirm(questionText);
if (confirmRequest) {
return true;
}
else {
return false;
}
}
To ask the user for a reply to the question asked. However, the confirm prompt appears but does not perform the displayVisualisation action!
Can anyone suggest why or help me implement this correctly?
In other examples, where the action is triggered by clicking a graphic, all is well.

Since you are using onclick, return true; in your confirmRequest function is simply allowing the rest of the clickHandler chain to be executed. I think you also need to explicitly submit the form at this time, in the true case.
Here is one way to do that, using only javascript:
function confirmRequest(questionText) {
var confirmRequest = confirm(questionText);
if (confirmRequest) {
document.forms[0].submit();
return true;
}
else {
return false;
}
}

Related

Disabling Form fields the use the SelectStatic widget in netbox v3 with javascript

I have a problem where i am trying to disable certain forms fields which use the SelectStatic Widget based on a tick box, i have included the javascript below.
const vlan = document.querySelector('#id_vlan');
const physical_facing = document.querySelector('#id_physical_facing');
const service_type = document.querySelector('#id_service_type');
const bd_function = document.querySelector('#id_function');
function vlan_enable(){
vlan.disabled = false;
};
function vlan_disable(){
vlan.disabled = true;
};
function service_function_enable() {
service_type.disabled = false;
bd_function.disabled = false;
};
function service_function_disable() {
service_type.disabled = true;
bd_function.disabled = true;
};
(function() {
service_function_enable();
vlan_enable();
if(physical_facing.checked){
service_function_disable();
} else {
vlan_disable();
}
})();
function pf_event() {
if(physical_facing.checked) {
vlan_enable();
service_function_disable();
} else {
vlan_disable();
service_function_enable();
}
};
physical_facing.addEventListener('change', pf_event)
When on the Page, the VLAN field is a DynamicModelFormField and will never disable, but when toggling the switch on and off the fields do not re-enable, i know the event is getting fired because i can see it in the developer tools, the disabled tag gets applied and removed with no change on the page, This may be a simple mistake but would like if someone can point me in the right direction.
below is what the page looks like
Netbox Page
Has anybody had any success doing this with the new version of netbox as it worked fine in V2 with the SelectStatic2 widget.

Use JavaScript to submit Ajax.BeginForm()

I'm typing this question away from my computer so I don't have the exact code, but the question might be straightforward enough without it.
When I have a submit button directly within an Ajax form and I click the button directly to submit, everything works fine, and as expected. The Ajax.Form POSTs back to the controller which returns a partial view that is rendered inside the current View that I have.
But what I need is for a button to be clicked in the Ajax.Form, and for a JavaScript function to run. The JavaScript function will do some vaildation which decides whether to submit the Ajax.Form or not.
I have tried putting 2 buttons in the Ajax.Form, a hidden submit button and a regular button. I used the onclick event of the regular button to call my JavaScript function which then called the click method of the hidden submit button. (I have also tried just submitting the Ajax.Form directly with document.forms[formname].submit() )
This sort of works.. But not correctly for some reason. The Ajax.Form POSTs back to the controller but when a partial view is returned from the controller, the partial view is the only thing rendered, and it is rendered as basic html with no css/bootstrap.
What is the difference between actually clicking the submit button and doing so programmatically?
How can Achieve what I am trying to do?
Edit
#using (Ajax.BeginForm("GetInstructorInfo", "Incident", FormMethod.Post, new AjaxOptions { OnBegin = "lookupInstructor();", UpdateTargetId = "InstructorInfo" }, new { #class = "form-inline", role = "form", #id = "instructorInfoForm", #name = "instructorInfoForm" }))
{
//code in here
}
Edit 2 / 3:
<script>
function lookupInstructor()
{
if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0) //Don't allow user to enter multiple instances of the same Instructor
{
document.getElementById("InstructorUsername").value = ''; //clear textbox value
return false;
}
var userInputInstructor = document.getElementById("InstructorUsername").value;
$.ajax({
url: '#Url.Content("~/Incident/LookUpUsername")',
data: { userInput: userInputInstructor },
success: function (result) {
if (result.indexOf("not found") != -1){ //if not found
$("#InstructorNotFoundDisplay").show();
document.getElementById("InstructorUsername").value = ''; //clear textbox value
$('#InstructorInfo').empty();
return false;
}
else {
$("#InstructorNotFoundDisplay").hide();
return true;
}
}
});
}
</script>
You can use the OnBegin() ajax option to call a function that runs before the form is submitted (and return false if you want to cancel the submit). For example
function Validate() {
var isValid = // some logic
if (isValid) {
return true;
} else {
return false;
}
}
and then in the Ajax.BeginForm() options
OnBegin = "return Validate();"
Edit
Based on the edits to the question and the comments, you wanting to call an ajax function in the OnBegin() option which wont work because ajax is asynchronous. Instead, use jQuery.ajax() to submit you form rather than the Ajax.BeginForm() method (and save yourself the extra overhead of including jquery.unobtrusive-ajax.js).
Change Ajax.BeginForm() to Html.BeginForm() and inside the form tags replace the submit button with <button type="button" id="save">Save</button>and handle its .click() event
var form = $('#instructorInfoForm');
var url = '#Url.Action("GetInstructorInfo", "Incident")';
var target = $('#InstructorInfo');
$('#save').click(function() {
if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0) {
....
return; // exit the function
}
$.ajax({
....
success: function (result) {
if (result.indexOf("not found") != -1) {
....
}
else {
$("#InstructorNotFoundDisplay").hide();
// submit the form and update the DOM
$.post(url, form.serialize(), function(data) {
target.html(data);
});
}
}
});
});

Load/Unload onClick Javascript

I have a code that was answered for me in another post which is below. However I have since ran into a new problem that I can't solve easily. I added additional LoadKML functions e.g. Function LoadKML1(), function LoadKML2(). The problem is now I need to click the killKML button to clear LoadKML1 before I can click LoadKML2. I would like to have the LoadKML1 clicked to load the KML and if clicked again LoadKML1 to run the killKML code. basically an on and off button in essence.
Any help is appreciated.
var kmlLoaded = false;
function LoadKML() {
alert('Kill KML');
if (kmlLoaded) {
return
killKML();
}else{
alert('Creating KML');
var nwlink = "http://kml-samples.googlecode.com/svn/trunk/kml/NetworkLink/placemark.kml"
createNetworkLink(nwlink);
kmlLoaded=true;
}
}
function killKML(source) {
ge.getGlobe().getFeatures().removeChild(networkLink);
you could change your code and call the killKML() in the kmlLoaded check like this:
function LoadKML() {
if (kmlLoaded) {
//return
killKML();
}else{
var newlink = "http://www.something.com/test.kml";
createNetworkLink(newlink);
kmlLoaded=true;
}
}

Modify an OnClick handler in JavaScript

I have a call to an onclick that is already created before.
The button already has an onclick, but I need to add one more parameter before it does the submit.
Here's the View Source Code on the button:
<td valign='top' align='right' >
<button name="Complete" title="Complete"
onClick="document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&target=step20&type=Full';
document.forms.Maker.submit();return false;">Complete</button>
</td>
This is a modification I made to add a confirmation after the user presses the button, and I also added so it shows what the onclick currently has:
function addEventConfirmation(element, type){
var old = element['on' + type] || function() {};
element['on' + type] = function () {
if (confirm("Are you sure?")){
old.call(this);
alert(old);
} else { return false; }
};
}
This is the alert from the before code:
function onclick()
{
document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full';document.forms.Maker.submit();return false;
}
The result should show something like this:
function onclick()
{
document.forms.Maker.action='http://example.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';document.forms.Maker.submit();return false;
}
Try this: make the action value a variable.
var oldURI = "http://mysite.com:8080..."
var href = "oldURI" + "&newParam=true"
document.forms.Maker.action='href'
If this Html is your own code, do just like this :
document.getElementById('Complete').onclick = function()
{
document.forms.Maker.action=
'http://mysite.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';
document.forms.Maker.submit();
return false;
}
else if you are trying to change this event handler from others website do this :
put website in an iframe named 'myframe' and code like this :
document.getElementById('Complete').onclick = function()
{
document.forms.Maker.action=
'http://mysite.com:8080/internal/Step.jsp?theId=19032&
target=step20&type=Full&newParam=true';
document.forms.Maker.submit();
return false;
}
but remember to turn cross-domain data source access restriction of your browser off !!!
for example in ie :
Internet Options -> Security -> Custom Settings (Internet Zone) ->
Enable Access data sources across domains

Javascript (jQuery) callback scope issue

The following is a little jQuery code that I wrote to check if a a username and email exists in database. If they do I return false to prevent submitting the form.
The way I planned it is something like this.
On submit after other stuff is valid. I use an ajax request to check if the username exists. If It does I then check the email in the same way.
And here is the problem. I cannot set the everythingIsOK inside the ajax callback. So if everything is ok I cannot return true.
Any ideas?
$(loginForm).submit(function(){
var = everythingIsOK = false;
if((loginForm).valid()){
$.get("/ajax/usernameAvailable", {username: $("#username").val()}, function(data){
if(data.available){
$.get("/ajax/emailAvailable", {email: $("#email").val()}, function(data){
if(data.available){
everythingIsOK = true;
return true;
}else{
$("#notAvailable").html("Email already exists.").show().fadeOut(8000);
return false;
}
}, "json");
}else{
$("#notAvailable").html("This is username already exist.").show().fadeOut(8000);
}
}, "json");
}
return everythingIsOK;
});
You can call the native form.submit() function (which won't trigger this handler again) if it is ok, and return false from the jQuery handler always, like this:
loginForm.submit(function(){
var form = this;
if(!loginForm.valid()) return false;
$.get("/ajax/usernameAvailable", {username: $("#username").val()}, function(data){
if(data.available){
$.get("/ajax/emailAvailable", {email: $("#email").val()}, function(data){
if(data.available) {
form.submit();
}else{
$("#notAvailable").html("Email already exists.").show().fadeOut(8000);
}
}, "json");
}else{
$("#notAvailable").html("This is username already exist.").show().fadeOut(8000);
}
}, "json");
return false;
});
When the check finishes (comes back from the server), you'll either get an error, or the form will submit and move on. Also I changed $(loginForm above to not be wrapped again, judging by if((loginForm).valid()){ (if that isn't erroring), it's already a jQuery object.
you have a syntax error on your second line:
var = everythingIsOK = false;
should be:
var everythingIsOK = false;
could that be the issue?
var = everythingIsOK = false;
should be
var everythingIsOK = false;
I guess. Maybe that's a first problem?
Instead of var = everythingIsOK = false; it should be var everythingIsOK = false;
Scope-wise, if that's not working, you can change it to be an attribute of an object var status = { everythingIsOK: false }; and change the value of that attribute.
However, you will need to always return false from your submit handler, because, as Nick points out, your get calls are asynchronous -- so they most-likely-will-not-have completed in time to prevent the form from submitting unless you do. (Take his advice and call submit manually from the interior get function's callback.)

Categories

Resources