JQuery get formaction and formmethod - javascript

I have the a like this one
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button" onclick="popisgolubova_radiobutton(this)">
<input name="rodovnik" type="button" formaction="rodovnik.php" formmethod="post" formtarget="_blank" value="rodovnik" class="button" onclick="popisgolubova_radiobutton()">
<input name="podaci" type="button" value="poodaci" formaction="podaciogolubu.php" formmethod="post" formtarget="_blank" class="button" onclick="popisgolubova_radiobutton()">
</form>
and javascript
function popisgolubova_radiobutton(element)
{
alert($(element).find("[formaction]").val());
var popisgolubova_radiobutton=$("input[name=RadioGroup1]").is(":checked");
if(popisgolubova_radiobutton==false)
{
alert("nop");
}
else
{
$("form#popisgolubova_form").submit();
}
}
First I'm checking if any checkbox is checked or not and if it is the I can submit the form. But the problem is formaction, formmethod and formtarget. how to get them and submit them

To get the action or method attributes of a form you can try something like below:
$(function() {
var action = $("#formid").attr('action'),
method = $("#formid").attr('method');
});

Hope this helps to get an idea to solve ur problem
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button postForm"/>
</form>
$(document).on('click', '.postForm', function () {
$('#popisgolubova_form').attr('action', $(this).attr('formaction'));
$('#popisgolubova_form').attr('method', $(this).attr('formmethod'));
$('#popisgolubova_form').attr('formtarget', $(this).attr('formtarget'));
});

So the question is talking about the unfortunately named
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction
...which is a way to override
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action
per clicking a properly set up submit button. The place you want to check this is upon submit - when you're sure things are actually being submitted.
The button you used to submit is stored as :focus - this does not seem to be otherwise stored in the event object at the moment.
$('form').on("submit", function(event) {
if( $(':focus').is('[formaction]') ) {
console.warn($(':focus').attr('formaction'));
}
if( $(':focus').is('[formtarget]') ) {
console.warn($(':focus').attr('formtarget'));
}
});

if( $(':focus').is('[formaction]') ) {
console.log($(':focus').attr('formaction'));
}

I had this problem and after searching the web I couldn't find a proper answer. Finally, I realized it's so simple.
When you add an event on form.submit you have an event argument that contains e.originalEvent.submitter, just use it as follows:
$('form').submit(function(e){
var url = form.attr('action');
if (e.originalEvent.submitter) {
var frmAction = $(e.originalEvent.submitter).attr('formaction');
if (frmAction)
url = frmAction;
}
,.....
});
You can use the samething for the formmethod as well.

Related

Placeholder only appears for split second [duplicate]

I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>

Action always going to Index using submit()

In my view, I'm using a function, submitForm(action) to submit the form on button click. This is one of many buttons that will use this function. The action parameter will indicate which controller method to use.
The function seems to generate the correct Action attribute (the path is correct in the console), but it is always directed to the Index method rather than the action parameter.
The button:
<input type="button" value="Save Only" id="save" onclick="submitForm('SaveOnly')" />
The function:
function submitForm(action) {
var $form = $("#myForm");
$form.action = ("/Area/MyController/" + action);
$form.submit();
}
You're not accessing the 'action' attribute of the form itself, but to the jQuery selector result, in order for your code to work, you need to access the DOM element from inside the selector with $form[0].
I recommend to stick to jQuery, you're already using it!. Below is a working code with jQuery selectors.
<form id="myForm"></form>
<input type="button" value="Save Only" id="save" data-action="saveOnly" />
<script>
$('#save').click(function(){
var action = $(this).data('action');
var $form = $("#myForm");
$form.attr('action', "www.google.com?q=" + action);
$form.attr('method', 'GET');
$form.submit();
});
</script>

Show submit when checkbox is checked loop

I've got a page in wordpress that displays around 20 poll questions (using WP-polls).
I'm using a snippet to display the submit button for each poll once an answer has been checked. Thing is, with this snippet I have to copy paste it about 20 times, because of that I some kind of loop.
This is the current code I'm using
$(document).ready(function() {
var $submit = $("#btn-7").hide(),
$cbs = $('input[name="poll_7"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-6").hide(),
$cbs = $('input[name="poll_6"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-5").hide(),
$cbs = $('input[name="poll_5"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
As you can see what changes is the "btn_number" ID and "poll_number". This goes on for another 20 snippets. How can I make this dynamic?
jQuery allows you to use wildcards, for example:
var $submit = $("#btn-*").hide(),
$cbs = $('input[name="poll_*"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
Edit: I see the wildcard selectors isn't supported by jquery anymore (as above example) you might want to look at: http://james.padolsey.com/javascript/regex-selector-for-jquery/ which gives you the ability to use regex to define the selectors for all btn's and code for it once
You can use the starts with selector on the ID and name attributes, to dynamically access the number. The change event is more appropriate than the click event for checkboxes.
Demo
$('[id^="btn-"]').hide();
$('input[name^="poll_"]').change(function(){
var number = this.name.replace('poll_', '');
$('#btn-' + number).toggle( $(this).is(":checked") );
});
It would be better to use data-* attributes to link the buttons and checkboxes, or nest them in an element that has the ID. Parsing the number out of the ID attribute isn't the cleanest way.
You don't have to repeat the same code for 20 times just for getting different button ids. you can make it dynamic. checkout this simple example
$("#submit").click(
function()
{
for(i=1;i<=5;i++)
{
msg = $("#btn-"+i).val()
alert(msg)
}
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="button" id="btn-1" value="button1">
<input type="button" id="btn-2" value="button2">
<input type="button" id="btn-3" value="button3">
<input type="button" id="btn-4" value="button4">
<input type="button" id="btn-5" value="button5">
<p>
<input type="button" value="submit" id="submit">
$(document).ready(function(){
for(var i=1;i<=20;i++){
var submit = $("#btn-"+i).hide(),
cbs = $('input[name="poll_'+i+'"]').click(function(){
submit.toggle($this.is(":checked"));
});
}
});

onClick and action html

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>
Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href
You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});
You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>
Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

When I use input type=button the value of it is not send to the server

In a form I have a button as input/submit. When I submit the value of the button is send.
if I change to input/button instead and do the submit via JQuery i.e. $("form").submit() the form is submitted but the value of the button is not send. Why? How could I fix this?
<form name="myform" id="myform" action="http://localhost/mypage.html" method="POST" >
<input type="button" id="btn" value="Actual value" name="save" >
</form>
$(document).ready(function() {
$("#btn").click( function() {
$("myform").submit();
}
}
buttons are not the same as inputs, that's why the button doesn't add to the form submission. you could add an input of type hidden with the value you want next to the button.
Otherwise you would have to use jquery to grab the button after the form has been submitted to get its value.
try with this code
$(document).ready(function() {
$("#btn").click( function() {
$("myform").submit();
});
});
You can use input="submit" button with preventDefault(); function if you want to conditionally check the form submission
$("#btn").click(function(event){
if(truePart){
$(this).unbind('click').click();
}else{
event.preventDefault();
alert("Please fill the required fields");
}
});
Try name="Actual Value" , then try accessing the value on server using POST['name'] , it will let you to have your actual value.
It looks like your javascript is syntactically incorrect.
Your code
$(document).ready(function() {
$("#btn").click( function() {
$("myform").submit();
}
}
should look like this
$(document).ready(function() {
$("#btn").click(function() {
$("myform").submit();
});
});
You're missing two closing parentheses and two semicolons.
If that doesn't help, try this for your button:
<input type="submit" name="save" value="Actual Value" />
Make sure your server-side code is prepared to accept a save parameter, as well. Can't send code to something that doesn't want to receive it!

Categories

Resources