Two jquery submits, one action per - javascript

I'm very new to JS/jquery (I'm a backend developer) and am having trouble implementing something. I am working with Django and have a template that has a text area that needs to have a submit event when the enter button is pushed. Here is how I've implemented that.
<div class="search multi-search">
{% if search_str %}
<textarea name="search_str" id="search_str">{{ search_str }}</textarea>
{% else %}
<textarea name="search_str" id="search_str" placeholder="Search by Lead ID's or email addresses separated by a comma."></textarea>
{% endif %}
<button id="thebutton" type="submit" class="btn btn-icon btn-large btn-inverse"><i class="icon-search"></i></button>
</div>
<script>
// overriding the default enter action to submit the
// search string on enter instead
$('#search_str').keydown(function(e){
// checks to see if the key pressed is the enter key and submit.
// (13 is the code for the enter key)
if (e.which == 13) {
e.preventDefault();
$('#leads_form').submit();
}
})
</script>
This submit populates a list where the user can select (via checkbox) a series of items. There is an action button for them to modify details of the selected items. When they press the action button a modal window pops up asking them to provide details regarding the changes requested. Here is my code for that piece.
<div id='give-reason' style="display: none">
<p>Give your reason for this change.</p>
<form>
<input type="text" id="reason">
<button type='button' id='reason-submit'>Submit your reason</button>
</form>
</div>
$('#reason-submit').submit(function(){
var lead_data = gather_lead_status($(this), update_type, true);
var reason = $('#reason').val();
lead_data(reason);
$.fancybox.close();
e.preventDefault();
});
This works wonderfully if I use .click() for the '#reason-submit' and the user clicks the submit button. If I use .submit() it does not work at all. First, if they click the submit button no action occurs (not surprising). Second, if they push enter the page refreshes - and all the data being displayed disappears.
Any suggestions on how I can solve this problem?
EDIT 1:
I should mention that I've tried to use $(':focus') and can't seem to get that to work. I could be using it incorrectly (wouldn't be surprising).
EDIT 2:
Thanks to asifrc and niiru I was able to get this working correctly with the following.
<div class="search multi-search">
{% if search_str %}
<textarea name="search_str" id="search_str">{{ search_str }}</textarea>
{% else %}
<textarea name="search_str" id="search_str" placeholder="Search by Lead ID's or email addresses separated by a comma."></textarea>
{% endif %}
<button id="thebutton" type="submit" class="btn btn-icon btn-large btn-inverse"><i class="icon-search"></i></button>
</div>
<div id='give-reason' style="display: none">
<p>Give your reason for this change.</p>
<form id='reason-submit'>
<input type="text" id="reason">
<button type='submit'>Submit your reason</button>
</form>
</div>
<script>
// overriding the default enter action to submit the
// search string on enter instead
$('#search_str').keydown(function(e){
// checks to see if the key pressed is the enter key and submit.
// (13 is the code for the enter key)
if (e.which == 13) {
e.preventDefault();
$('#leads_form').submit();
}
})
$('#reason-submit').submit(function(e){
e.preventDefault();
var lead_data = gather_lead_status($(this), update_type, true);
var reason = $('#reason').val();
lead_data(reason);
$.fancybox.close();
});
</script>

The submit event can be binded to only certain type of elements.
From the jQuery api docs http://api.jquery.com/submit/ :
The submit event is sent to an element when the user is attempting to
submit a form. It can only be attached to <form> elements. Forms can
be submitted either by clicking an explicit ,
<input type="image">, or <button type="submit">, or by pressing Enter
when certain form elements have focus.
So try changing the type attribute of your button to "submit" and see if that works.
Better yet, just give your form tag an id and try attaching to the submit event for that..
Let me know if that helps :)

.click() works for obvious reasons. But, pressing enter will trigger the submit action, which will post the form. Instead, change your button type to submit, and prevent the default action of the submit event. This will handle you for any action that could trigger submitting the form.
<div id='give-reason' style="display: none">
<p>Give your reason for this change.</p>
<form>
<input type="text" id="reason">
<button type='submit' id='reason-submit'>Submit your reason</button>
</form>
</div>
$('#reason-submit').submit(function(event){
event.preventDefault();
var lead_data = gather_lead_status($(this), update_type, true);
var reason = $('#reason').val();
lead_data(reason);
$.fancybox.close();
e.preventDefault();
});

Related

Flask/html - submit only one button on Enter key

I have folowing form:
<form method="post">
<input type="submit" name="submit" value="Save" class="button">
<input type="text" name="search_input" id="search_input">
<input type="submit" name="submit" value="Search" id="searchBtn" class="button">
</form>
Desired behavior is that when I enter some text to input field and hit Enter key, form shall post submit/Search and search_input.
Instead I get two separate posts:
request.form['submit'] =
ImmutableMultiDict([('submit', 'Save'), ('search_input', 'exampletext')])
ImmutableMultiDict([('search_input', 'exampletext'), ('submit', 'Search')])
I also tried to use following js, but the result is same:
var input = document.getElementById("search");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchBtn").click();
}
});
Do you have any idea, what's wrong and how to fix it?
From your js script i understand that you want the form to only click search and not save when you press the enter key?
If that is so then you need to change the name of the two buttons because form submit uses the name attribute to identify elements.
Since both your inputs have the same name you get two posts.
Edit: I just found out that the first submit in the form is clicked by default when you press the enter key (Without needing any js code), So in your case when you press the enter key the first button (Save) is pressed by default and from your js script the second button (Search) is pressed.
So you just have to put the search button on top of the save button and use CSS to change the order in the webpage

Jquery- Form doesn't get my input value in first time

I have a form which has 2 inputs, really simple.
<form class="cform">
<input type="text" name="cname" class="cname" id="cname" autofocus placeholder="Firstname Lastname">
<div class="floatl regards"><input type="submit" value="Submit" class="submit" id="submit"></div>
</form>
My JQuery is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$("#submit").click(function()
{
var CName = $("#cname").val();
console.log(CName);
});
</script>
My problem is when I add a word in textbox and click on submit button it doesn't show anything in console unless I type the same word again and submit it! And it works on second click.
I notice that it doesn't work untile it add that words in the URL and I should write exactly the same word for the second time and click on submit if I want it to work!
How can I fix this error? which part of my code is wrong!?
The click on your button will submit the form using GET method to the current page that why you saw the word on the link after the click, all you need to prevent that is to change the type of button to button instead of submit, that will prevent the page from refresh :
<input type="text" name="cname" class="cname" id="cname" autofocus placeholder="Firstname Lastname">
Or you could add e.preventDefault() or return false; instead in your js code :
$("#submit").click(function(e){
e.preventDefault(); //That will prevent the click from submitting the form
var CName = $("#cname").val();
console.log(CName);
return false; //Also prevent the click from submitting the form
});
Hope this helps.
$("#submit").click(function(){
var CName = $("#cname").val();
console.log(CName);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cform">
<input type="text" name="cname" class="cname" id="cname" autofocus placeholder="Firstname Lastname">
<div class="floatl regards"><input type="button" value="Submit" class="submit" id="submit">
</div>
</form>
When you click the submit button the page will reload and your jQuery definition won't be recognized. In order to prevent that use a html button instead of a input submit button.
Or you can use e.preventDefault(); inside your function call that will prevent to submit the form. In order to use that you have to pass the event as parameter using function(e) {}

Enable submit button only when there are characters in textarea

I'm working on a basic form that has one textarea and one submit button:
<form action="admin-post.php" method="post">
<textarea style="width:630px;" aria-hidden="true" class="wp-editor-area" rows="6" autocomplete="off" cols="71" name="author_message" id="author_message"></textarea>
<p class="submit">
<input type="submit" value="Post Message" class="button button-primary" id="submit" name="submit">
</p>
</form>
I want the submit button to be enabled only if there is some text entered within the textarea. How can I do this using Javascript?
Note that I cannot change the the value or HTML code of the submit button.
If you need continuous verification solve it like this (without changing the button attributes):
<textarea style="width:630px;" aria-hidden="true" class="wp-editor-area" rows="6" autocomplete="off" cols="71" name="author_message" id="author_message" onkeyup="if(this.textLength != 0) {submit.disabled = false} else {submit.disabled = true}"></textarea>
and modify the body tag:
<body onload="submit.disabled = true">
Cheers
JSFiddle
edit:
If you cannot modify the body tag, just add the disabled attribute to the button.
Working code here JSBIN :) i used HTML Disable attribute
You need to find the submit button in the DOM first and disable it and then attach an event listener to the textarea, wherein you disable/enable the submit button based on whether the textarea is empty or not:
document.getElementById("submit").disabled = true;
document.getElementById("author_message").addEventListener('change', func, false);
function func(){
document.getElementById("submit").disabled = (document.getElementById("author_message").value==='') ;
}
Here is the JsFiddle.

Force form to send certain submit button through (when there are multiple) when ENTER key pressed

I have a form with two submit buttons, name="submit_button" and name="search_me_logo", and when the form arrives at the action location, it does two different things depending on which button was pressed.
When the enter key is pressed, I want it to do the same thing as the name="submit_button" but right now it seems to be sending the name="search_me_logo" by default.
Here's the HTML code you need:
<form action="/search_me.php" method="GET">
<div id="search_me_outer_div">
<button id="search_me_div" name="search_me_logo" type="submit">
<img id="search_me_image" src="/images/header/search_icons/search_me.png" height="33" alt='"search me"'/>
</button>
</div><!--
--><div id="search_box_outer_div">
<div id="search_box_div">
<input id="search_box" onfocus="hidePlaceholderAndShineBox();" onblur="showPlaceholderAndBlurBox();" name="search" type="text" spellcheck="false" size="32" placeholder='Get to know Sam... "search me"'>
<button id="search_div" name="submit_button" type="submit">
<img id="search_img" src="images/header/search_icons/fancy_search.png" height="21" alt="Go"/>
</button>
</div>
</div>
</form>
PHP:
if (isset($_GET['submit_button'])) {
echo 'submit was pressed<br>';
} else if (isset($_GET['search_me_logo'])) {
echo 'logo was pressed<br>';
} else if (isset($_GET['search'])) {
echo 'enter was pressed<br>';
} else {
//show error page
}
Right now when I press enter, it echos "logo was pressed". There is probably a way with JavaScript, but if it's possible simply with HTML/PHP, that would be wonderful.
By default, hitting the enter key will cause the first submit button. You can simply add the default submit action in a hidden div right at the beginning of the form. For example:
<form action="/search_me.php" method="GET">
<div style="height:0px; width:0px; overflow:hidden;"><button id="search_div" name="submit_button" type="submit"></button></div>
and keep the rest as is.
Edit: some browsers won't let the enter key to trigger the first button if it's not displayed (e.g. display:none;).
However it will work with:
width: 0;
height: 0;
overflow: hidden;
In the CSS of the element that contains the hidden submit button.
Thanks for all the suggestions. #NoGray's answer could work or I just did two forms, as #Irdrah suggested.
Each forms' buttons and inputs had different names, and one of the inputs had a type="hidden" and id="hidden_input". Then when the submit for the form with the hidden input was clicked, I used jquery's submit() to set
document.getElementById('hidden_input').value = document.getElementById('shown_input').value;`
and returned true. I haven't tried #NoGray's but I'm sure it would work.

How do I detect how a form was submitted via JavaScript?

I have a form with multiple submit buttons and I'm listening for the 'submit' event via JavaScript. I want to know which submit button or form field (if the user pressed 'Enter/Return') triggered the submit event. Is there a way to get the HTML element that the user clicked on or pressed 'Enter/Return' in?
Update since people aren't understanding me:
This is via JavaScript before the form is submitted. No server-side detection allowed. I also need to handle the form being submitted via the user pressing Enter or Return.
Code
<form action="" method="POST">
<input type="text" name="first_name">
<input type="text" name="item">
<input type="submit" value="Add item">
<input type="submit" value="Submit">
</form>
Clicking 'Add Item' or pressing Return/Enter inside name="item" will add another form field.
Final Note
As far as I can tell, there isn't a way to detect which form field triggered a form submission. If you need to prevent submitting a form that has multiple buttons and/or from Enter/Return, you'll need to use <input type="button"> and bind event handlers to the form fields you want to stop form submission from.
If you have multiple submit buttons, the way you can tell is by giving each of them a unique name attribute, like this:
<input type="submit" name="submit1" value="Submit 1"/>
<input type="submit" name="submit2" value="Submit 2"/>
<input type="submit" name="submit3" value="Submit 3"/>
The one that is focused is sent along with the form submit, so if you clicked the one with a name of "submit2", that would come through in the form POST (or GET). If enter is hit, the first button in the source (in this case submit1) is considered the default and is sent along. You could set it to display:none to use as a dummy for detecting whether enter was pressed vs actually clicking a submit button.
EDIT:
In response to your comments, to capture the enter key getting pressed in certain elements you can do this with jQuery.
Note, you'll need to give first_name and add_item id attributes, and turn add_item into a type="button" instead of type="submit".
HTML:
<form action="" method="POST">
<input type="text" name="first_name"/>
<input type="text" id="item" name="item"/>
<input type="button" id="add_item" value="Add item"/>
<input type="submit" value="Submit"/>
</form>
JS:
$("#item").keydown(function(event){
if(event.keyCode == 13) {
addFields();
event.preventDefault();
event.stopPropagation();
}
});
$("#add_item").click(function(event) {
addFields();
});
You could set the onclick event on each element you are interested and call a javascript function with a different parameter for each element clicked.
From that function you send the idendifier of the button to the server side as a parameter
Just put a different name on each submit button, whichever one was clicked will be submitted (i.e. its name/value pair) with the form. Forms have worked like this since the begining of (WWW) time.
If the form is sumitted by enter or other keypress, no the first submit button name/value pair will be submitted.
Edit
Re-reading your question, you may want to determine how the form was submitted before it is sent. A click listener on the form can remember the last submit button clicked, but in Firefox, pressing enter in an input dispatches a fake click on the first submit button so you can't detect it.
I think you can't do it reliably other than using the basic method suggested above or Jordan's hidden submit button. If you say why you need to do this, perhaps more help can be provided.
here's an option if you don't mind using jQuery:
example: http://jsfiddle.net/U4Tpw/
use something like
$('form').submit(function() {
// identify the form by getting the id attribute
handleWhichForm($(this).attr('id'));
});

Categories