Which submit button was pressed? - javascript

In this jsfiddle
http://jsfiddle.net/littlesandra88/eGRRb/
have I submit buttons that are auto-generated. Each table row gets an unique ID number, and if needed each submit button can get the same unique number as well.
Question
The problem is that there are multiple submit buttons, so how do I know which was pressed?
HTML
<form action="" method="post">
<table class="alerts tablesorter" id="accTable" cellspacing="0">
<thead>
<tr class="header">
<th class="activity-header"> A </th>
<th class="activity-header"> Signed </th>
<th class="activity-header"> </th>
</tr>
</thead>
<tbody>
<tr class="row" id="7249">
<td class="activity-data">7249</td>
<!-- tablesorter can't sort a column with check boxes out-of-the-box, so it needs something to sort on. That is why the span tag is here -->
<!-- a jquery script is watching the state of the checkbox, so when clicked the value in the span is updated -->
<td class="checkbox"> <span style="display:none;">0</span> <input name="signed" type="checkbox" > </td>
<td class="edit-column"> <input value="Save" type="submit" name="7249"></td>
</tr>
<tr class="row" id="61484">
<td class="activity-data">61484</td>
<td class="checkbox"> <span style="display:none;">1</span> <input name="signed" type="checkbox" checked > </td>
<td class="edit-column"> <input value="Save" type="submit" name="61484"></td>
</tr>
</tbody>
</table>
</form>
JavaScript
$(document).ready(function() {
$("#accTable").tablesorter();
// :checkbox stops from executing the event on the save button. Same as input[type=checkbox]
$('#accTable input:checkbox').click(function() {
// insert 1 or 0 depending of checkbox state in the tag before the input tag. In this case <span> is before <input>
// this is done so tablesorter have something to sort on, as it doesn't support checkbox sort out of the box.
var order = this.checked ? '1' : '0';
$(this).prev().html(order);
$(this).parents("table").trigger("update");
});
});
// sends the form content to server side, and stay on page
$('form').live('submit', function() {
alert('test');
// don't redirect
return false;
});

You could use delegate():
$('form').delegate('input:submit','click',
function(){
alert(this.name);
return false;
});
JS Fiddle demo.
Edited to address question in the comments, from OP:
Would it be possible to display 0 or 1 as the state of the associated checkbox with this approach?
Yeah, that's possible, though it's a little more long-winded than I'd like:
$('form').delegate('input:submit','click',
function(){
var idString = this.name;
var checkboxState = $('#' + idString).find('input:checkbox').is(':checked');
if (checkboxState == true){
alert('1');
}
else {
alert('0');
}
return false;
});
JS Fiddle demo.

You will need to add an onClick handler to each button that does:
$(this).closest('form').data('submit_name', this.name);

Assign a function to the click event of the submit buttons. That function should simply store the clicked button's value in a variable. Inside the submit event of the form, check the value of that variable. The submit event will fire after the click event so you should be able to get the expected result.
Demo here
The thing to note here is that that different browsers behave differently when dealing with multiple submit buttons; specially when you hit enter to submit the form. I think my example takes care of this.

As you are using one form and using $('form').live('submit', function() { and both submit buttons are in the same form so its not possible in submit event. You have to use click event or two form tags.

Here is how I solve this,
HTML
<form id="my-form" ...>
....
Save
Save and add another
</form>
Javascript
$('.btn-submit-form').on('click', function(ev){
ev.preventDefault();
var $form = $(this).attr('href');
if ($form.length > 0) {
$form.trigger('submit', {'submitBtn': $this});
}
});
$('form').on('submit', function(ev, extra) {
if (extra && extra.submitBtn) {
var submitVal = extra.submitBtn.attr('data-value');
} else {
var submitVal = null;
}
// submit the form as you want with submitVal as one of the fields.
});
The advantage here is that your form only submits on the submit event and not on click event. This way you can have one common function to submit the form whether you click a button, hit return in a form field or submit it pragmatically.
I also like to make things as generic as possible and turn them into patterns. This two functions can work across your whole project if you come up with some patterns like naming each submit button with value as .btn-form-submit and having a data-value attribute to store the value.

Related

Custom prompt box using javascript and CSS

I am working on a custom prompt box. So far I used a hidden div that is shown on a button click with javascript:
function openPromptBox() {
var pos = FindXY(document.promptForm);
var cont = $('promptContainer');
var searchBox = $('promptBox');
searchBox.style.left = (pos.x - 20) + "px";
searchBox.style.top = (document.body.scrollTop + 100) + "px";
cont.style.display = "block";
}
here is the div:
<div id="promptContainer">
<div id="promptBox">
<table>
<tr>
<td colspan="2">
<input type="text" name="result" id="result" size="25"/>
</td>
</tr>
<tr>
<td>
<input type="button" id="btnOK" value="OK" />
</td>
<td>
<input type="button" id="btnCancel" value="Cancel" />
</td>
</tr>
</table>
</div>
</div>
Now I need to return to the function openPromptBox the value of textbox result whenever btnOK button is clicked. Is there any way to do that?
No, this is impossible.
A prompt opens a modal dialog and blocks all further JavaScript (and interaction with the page) until one of the buttons is activated by the user.
When you insert form fields into an HTML document, there is no blocking (nor could there be, since that would prevent the user from filling in the form).
You need to bind an event listener to the form fields you have created and then handle the response going forwards just like any other asynchronous operation.
It seems like you are using jquery so here would be a solution:
$('#result').val()
Would take the current value (the text / number / etc) out of your input
now you can simply pass it to your function like so:
$('#btnOK').on('click', function() {
openPromptBox($('#result').val());
});
That's it.
In the definition of your function you should probably add a parameter which is then used in the function:
function openPromptBox(textFromInput){
alert(textFromInput);
}
JSFiddle: https://jsfiddle.net/01bkkgzd/2/
UPDATE:
Without JQuery it would be:
document.getElementById("result").value
which will get the value of the input
Example for the onclick action and the following function call
document.getElementById("btnOK").addEventListener('click', function() {
openPromptBox(document.getElementById("result").value);
});
JSFiddle: https://jsfiddle.net/01bkkgzd/5/

How can I target EVERY link and button on the page?

I have a shopping cart that contains a form field and a checkbox in each row. The form field controls the quantity, which can be edited, if the customer wants to modify the quantity of the product they order, and the checkbox selects the item, either to toss the item in a wish list, or to remove it. The Add To Wish list and Remove Functions are separated out of this particular question.
What, I am looking at doing, is detecting when the form has been changed, and then targeting EVERY anchor tag and button on the page, so if the items have been modified, the script stops the click through and pops up a bootstrap modal, alerting the user that something in their cart has been modified.
HTML (the shopping cart row, run through a JSTL forEach loop, but the markup is this):
<table>
<form id="shoppingCart" action="updateTheCart.action">
<c:forEach var="item" items="${shoppingCart.items}" varStatus="status">
<tr class="cart-row">
<td class="remove" data-label="Remove">
<label>
<input type="checkbox" name="removeFlag(<c:out value="${status.count}"/>)" value="true"/>
</label>
</td>
<td class="title" data-label="Title">
${item.value.sellableGood.name}
</td>
<td class="qty" data-label="Quantity">
<input type="num" class="form-control qty-input" name="quantity(<c:out value="${status.count}" />)" value="<c:out value="${item.value.quantity}" />"/>
</td>
<td class="subtotal" data-label="Line Total">
<fmt:formatNumber type="currency" pattern="$#,##0.00" value="${item.value.itemExtendedTotal}" />
</td>
</tr>
</c:foreach>
</table>
<p>Checkout</p>
<p><button type="submit" id="checkout">Update Cart</button></p>
<p><button id="addToWishlist" type="submit" id="wish-list">Add To Wish List</button></p>
<p>Chontinue Shopping</p>
</form>
JS:
$("#shoppingCart :input").change(function() {
$("#shoppingCart").data("changed",true);
});
I know I am missing a LOT, but I really don't know where to begin at this point.
You can try the onbeforeunload Event
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
Javascript:
;[].forEach.call(document.querySelectorAll('a, button'), function(element) {
//do something with buttons and links, for example:
element.setAttribute('data-changed', true')
});
The jquery equivalent is:
$('a, button').each(function(element) {})
To watch the form for changes, I would use the blur event, it's the reverse of focus:
;[].forEach.call(document.querySelectorAll('#myForm input'), function(element) {
element.addEventListener('blur', function(event) {
//something has changed
})
});
Jquery:
$('#myForm input').on('blur', function(event) {})

jQuery keeps number of cloned rows after reset

I have a form in a popup, that presents a simple table with header and one row, with a + button the user can click to add (clone) a row.
This works perfectly, the user submits the form, data is read - no problem.
The form is reset after submission with:
$('#entryTable').find("tr:gt(1)").remove(); // keep header and first row
$('#entryForm')[0].reset();
If the user calls the form immediately, the forms "seems" correctly reset, all fields look like new.
If the user clicks on the + (clone) button - it adds the number of rows added previously, and not 1, as if something (but what ?????) was not reset.
my clone function is
$(".cloneprod_add").on('click', function(e) {
e.preventDefault();
var $tr = $(this).closest('.tr_clone'); //only first row has +
var idtr= parseInt($tr.attr("id")); // checked it is always id of row1
var $clone = $tr.clone(true);
cindex++;
$clone.find(':text').val('');
$clone.attr('id', idtr+(cindex) );
$clone.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cindex);
}
});
$tr.after($clone);
$("#addline_"+cindex).addClass("uk-hidden"); // remove +
$("#delline_"+cindex).removeClass("uk-hidden"); // add -
});
cindex is correctly reset to 0 when the form is called again. What else should be reset ? where is my error ?
Thanks for your advices
(EDIT)
I am adding the form . I am using UIkit (www.getuikit.com), a node server and the form comes from a template in jade - I copied the HTML from the browser
<form id="entryForm" action="" class="uk-form uk-form-stacked" >
<div id="entryDialog" class="uk-modal-dialog uk-modal-dialog-large">
<fieldset data-uk-margin="">
<div class="uk-panel uk-panel-box uk-panel-box-primary uk-margin-small-top">
<div class="uk-form-row"><div class="uk-grid"><div class="uk-width-1-1">
<table id="entryTable" class="uk-table">
<thead><tr><th>lot</th><th>code</th><th>num</th>
<th>qte</th><th>unit</th><th>pos</th><th>cont</th>
<th></th></tr>
</thead>
<tbody><tr id="0" class="tr_productclone">
<td><input type="text" name="lot" id="lot_0" class="lot"></td>
<td><input type="text" name="code" id="code_0" class="code"></td>
<td><input type="text" name="num_0" id="num_0" class="num"></td>
<td><input type="text" name="qte_0" id="qte_0" class="qte"></td>
<td><select name="unit_0" id="unit_0" class="unit"><option value="items">pezzi</option></select></td>
<td><select name="pos_0" id="pos_0" class="pos"><option value="1">piece1</option></select></td>
<td><select name="cont_0" id="cont_0" class="cont"></select></td>
<td><button id="addline_0" class="uk-button cloneprod_add"></button>
<button id="delline_0" class="uk-button cloneprod_del"></button></td>
</tr>
</tbody></table></div></div></div></div>
<div class="uk-modal-footer"><button id="btnSave" type="submit" class="uk-button ">save</button></div>
</fieldset></div></form>
I found a solution to my problem. I don't know the why and hows, but at least it works.
I had the impression that the remove was keeping the information of the number of cloned rows and was thus putting that number back. I thought about reloading the table in the modal, so that it would be "fresh without memory".
In the end, I wrote the definition of the table in the js script and not in the Jade template. The table is rebuilt overtime the form is called, and no more memory ghosts.
It works, but I still don't understand why those ghosts.

jQuery, javascript: several forms same submit button text - how to determine value of closest hidden value box

I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}

how to identify submit() that arrived from javascript method(not button) in asp.net

I have a list of users that in the end of each line in the table I added two links("href"):
one for "update" user and secend for "delete" user.
So for enable that I added a call to javascript function that capture the ID of user
and insert it to some form that I created before (form with only one "hidden" field),
and then the function activated submit() operation to the server part (asp.net code).
I checked and the submit() operation works ok(checked with respons.write()...)
But I know how to recognize a submit form button inside IsPost by ask what the value
of the submit button (for example: if(Request.Form["ExpertButton"]== "delete"){..some code here....})
But when I activate submit() with javascript, how could I recognize post?
I tryed with the value of the hiiden field but it's not capture this
and it skiped of the if statement....
the list of users code:
foreach(var row in db.Query(displayExperts,nameOfExpert))
{
<tr>
<td class="dispExpertActScreen">#row.ExpertID</td>
<td class="dispExpertActScreen">#row.name</td>
<td class="dispExpertActScreen">#row.password</td>
<td class="dispExpertActScreen">#row.allowBonds</td>
<td class="dispExpertActScreen">#row.allowStocks</td>
<td class="dispExpertActScreen">#row.allowExchangeTraded</td>
<td class="dispExpertActScreen">#row.allowMutualFund</td>
<td class="dispExpertActScreen">update</td>
<td class="dispExpertActScreen">delete</td>
</tr>
}
the form code:
<form method="post" name="deleteExpert" style="font-size: medium; margin-top: 10%" dir="rtl">
<input type="hidden" name="expertID" id="expertID" value="">
</form>
the javascript code:
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('deleteExpert').submit ();
}
</script>
the asp.net code:
#{
var db = Database.Open("MyProjectSite");
var display="no";
var displayExperts="";
var nameOfExpert="";
var category="";
if(IsPost)
{
if(Request.Form["ExpertButton"]== "search")// this is by button!!!
{
some code.....
}
//Response.Write("^^^^^^^^^^^^^^^^^^^^^");
if(Request.Form["ExpertButton"] != "")// this need to be by javascript submit() method !!! here I need to recognize it.
{
var id=Request.Form["expertID"];
Response.Write("^^^^^^^^^^^^^^^^^^^^^"+id);
var deleteQuery="DELETE FROM InvestmanExperts WHERE ExpertID=#0";
db.Execute(deleteQuery,id);
}
}
db.Close();
}
thanks...
Why not puting another hidden input value :
<input type="hidden" name="txtJavascriptMode" id="txtJavascriptMode" value="">
then in your javascript code :
<script>
function expertToDelete(expertID) {
document.getElementById('expertID').value = expertID;
document.getElementById('txtJavascriptMode').value = 'true';
document.getElementById('deleteExpert').submit ();
}
</script>
and in your serverside you can checkout
if(Request["txtJavascriptMode"] == "true")
{}

Categories