AlpineJS submit form on button click posts the old value instead of the new one - alpine.js

I'm new to alpineJS, so this might be a silly question. I try to increase an input field by 1, and submit the new value (preferably with a small delay).
I currently have:
<input type='button' value='+' class='qtyplus plus' field='quantity' x-on:click="qty++ && $event.target.form && $event.target.form.dispatchEvent(new Event('submit'));" />
This increases the value of the input form by 1, and submits the form. The problem is that the submitted value is the old value, and not the new one.
Any help with this is much appreciated!

The && operator in JavaScript is used to test conditions for true/false. You should instead use ; to put multiple commands in a single click. JavaScript does some unexpected conversions of values to true/false values. I'm surprised it works even partially. The mysteries of JavaScript! 😆
MDN has some good info on the && operator - called Logical AND
Here's your code sample with the change. I also made a couple of other changes using Alpine JS features:
debounce might be useful for you as it tells Alpine JS to wait until the user has stopped clicking before it executes the click code - which means your server won't have to process so many requests.
x-ref can be used instead of $event.target.form (not useful for you I think, but might be useful for others reading this question)
Form elements have a submit() method you can use. MDN has good info on this as well.
<form x-ref="myform">
<input
type='button'
value='+'
class='qtyplus plus'
field='quantity'
#click.debounce="qty++; refs.myform.submit()" />
</form>

After some more debugging I found the solution by using two on-click events, one that works directly and one that is delayed. This solved the issue for me.
<input type='button' value='-' class='qtyminus minus' field='quantity'
x-on:click="qty--;" #click.debounce.2000ms="$event.target.form.submit();"/>

Related

Dijit form stops validating when mvc Group is used in it

I have a page which uses dijit/form/Form to validate all of the form widgets in it.
Validation works correctly if I put widgets directly under the Form (tag).
Once I surround the widgets with a dojox/mvc/Group (within the form), Form validation stops completely and none of the widgets seem to validate when I call Form::validate().
Debugging the Dojo code shows that nested widgets are never considered validatable in the Form so when I surround widgets with Group they get excluded from validation.
Is there a workaround for this?
AFAICT from dijit/form/_FormMixin#_getDescendantFormWidgets() and dijit/_WidgetBase#getChildren(), the issue can be solved by adding data-dojo-mixins="dijit/_Container" to the element having data-dojo-type="dojox/mvc/Group".
Also (though I'm not sure if it meets your requirement), dojox/mvc/tests/test_mvc_new_loan-stateful.html example shows form validation solution with dojox/mvc.
Hope it helps.
Best, Akira
It seems like there is no easy way to solve this with dijit/form/Form. At the very least, it should be subclassed or monkey-patched to make it consider nested widgets.
However, it seems that dojox/form/Manager handles nested widgets properly, so I have switched to it.
Switching to Manager required some refactoring since it cannot be simply converted into an object with dom-form (dijit/form/Form can be converted).
HTML code before:
<div
id="_pg_detailForm"
data-dojo-type="dijit/form/Form"
encType="multipart/form-data"
action="" method=""
>
... form widgets (surrounded with MVC Groups...etc)
</div>
After:
<form id="_pg_detailForm">
<div
id="_pg_detailFormManager"
data-dojo-type="dojox/form/Manager"
>
... form widgets (surrounded with MVC Groups...etc)
</div>
</form>

jQuery - detecting if a button has been pressed

You'll have to forgive me for asking a somewhat trivial question here, but I'm generally curious if there's a better way of detecting if a button has been pressed. I'm guessing this would apply to anchor tags also.
Presently I have two submit buttons (so I cannot use $(form).submit in this case), both of which will change another field when they are activated:
<button id="accept" type="submit">Accept</button>
<button id="decline" type="submit">Decline</button>
To achieve this I have detected a click event, and the Enter keypress event separately:
$('#accept').click(function(){ $('#decision').val('Agree'); })
$("#accept").keyup(function(event){
if(event.keyCode == 13){
$('#decision').val('Agree');
}
});
I guess more than anything I'm wondering if there is a way to simplify this code, as it's rather cumbersome, especially if there's a lot of processing (you could create a function, but that's yet another step) and since jQuery seems to have most things covered, I'm surprised after trawling the internet I can't find a cleaner solution.
(with the above I was worried about other ways to mimic the button press, such as hitting space, although that seems to be covered!)
Thanks!
For a button element, both the spacebar and the enter key being presses on a button will generate a click event according W3C event specifications. You should not have to do any special processing to handle that.
As for using $(form).submit(), you can. Just change your buttons to not implicitly submit the form by chaning them to push buttons (W3C):
<button type="button" id="...">...</button>
Then in your handler you can do:
$('#accept,#decline').click(function(event){
$('#decision').val($(event.target).text());
$(form).submit();
}
If you need to you can do some processing on $(event.target).text() to make 'Decline' null/emptystring if necessary.
you can do something like this to make the click a little better: (using a function is necessary here to get something better):
function setDecision(value){
$('#decision').val(value);
}
$('button[type=submit]').click(function() {
var val = $(this).text();
setDecision(val);
});
$("button[type=submit]").keyup(function(event){
var val = $(this).text();
if(event.keyCode == 13){
setDecision(val);
}
});
I think I understand your question, and there may be some precedence to be found in this related topic.
jQuery: how to get which button was clicked upon form submission?
This method avoids adding the .click() event to each button, though that may be a viable option for your application.
Hope this helps!
Mason
Add name="decision" and value="Accept" / value="Decline" (accordingly) to the submit buttons
This way you do not need javascript to handle this at all...
And if the 'Accept' button is the first, then pressing enter inside any form field will also trigger that one
Sample:
<form action="1.html" method="get">
<input type="text" name="in">
<button type="submit" name="decision" value="Accept">Accept</button>
<button type="submit" name="decision" value="Decline">Decline</button>
</form>

How to recognaize which ajax form it is in Django?

I have view which takes care of all the Ajax submits from the client side. And to differentiate them by I uses different submit button names such as this one
<input type="submit" value="Send" name="send_message">
Suggested from this question.
The only problem is that from the view side it doesn't seems to carry the name to the server side so I cannot use the following if-statement
if 'send_message' in request.POST:
It works if I send it normally with page fresh. But I want to use it with Ajax.
I came up with a hack that you can add this name with jQuery. Simply by after serializing() your data you then concatenate the name attribute by data += "&send_message"
Then the if statement will work. But it doesn't seems so clean. So I wonder if there's a better way to handle this? Or should I make different views to handle the different Ajax calls I have?
You really should post each form to a different URL.
If not, you could add a hidden input with the name of the form as the value.
<input name="form_name" type="hidden" value="form_1" />
views.py:
form_name = request.POST['form_name']

Selenium File upload

How to automate Uploading a file using selenium.
How to give file Path ??
My TextBox is Readonly. I cant type the file path directly in the textbox.
Also, how to stop the selinum server until that file completely uploaded.??
My File upload field is a invisible field. And i found its code using firebug add on.
Before adding a file code is like this.
<input id="ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState" type="hidden" name="ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState" autocomplete="off" value="{'isEnabled':'true','uploadedFiles':[]}">
And after adding a file(doc file). The code changed to
<input id="ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState" type="hidden" name="ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState" autocomplete="off" value="{'isEnabled':'true','uploadedFiles':[{"fileInfo":{"FileName":"scope.docx","ContentType":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","ContentLength":12887},"metaData":"/wEFsAF7IlRlbXBGaWxlTmFtZSI6ImZyeWd1NGNqLmt1YSIsIkFzeW5jVXBsb2FkVHlwZU5hbWUiOiJUZWxlcmlrLldlYi5VSS5VcGxvYWRlZEZpbGVJbmZvLCBUZWxlcmlrLldlYi5VSSwgVmVyc2lvbj0yMDExLjEuNTE5LjM1LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTEyMWZhZTc4MTY1YmEzZDQiffOraDjiYXPavAAMYOUAVVhGEKk8"}]}">
What is the Xpath here?
I tried with xpath id="ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState". The code which i used is
selenium.type("id="ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState","c:\\docfile1.doc");
But its not working.
Help Me..
The XPath expression for this input would be //input[#id='ctl00_ContentPlaceHolder1_AsyncfileUpload_ClientState'].
However, I fear this won't work since Selenium usually refuses to work with invisible elements. Also, hidden <inputs> are usually just containers for pre-filled data or containers for script-validated-and-edited data.
You should be looking for a <input type='file' /> if there's some, or maybe a javascript handling the click on the enclosing element (but, frankly, that's usually not the case - the scripts tend to act on edit of the input, not on the click on them).
If you can't find it, post some more code. The best thing would be a SSCCE, so take the source of the page and make it naked, strip everything unnecessary for us from it. We love code. And we love anything that's naked.
And about the wait for the upload to be complete: There's no such default thing. If the file is sent during a usual form upload (by clicking the Submit button), then the browser will wait. If it is uploaded immediately, you'll have to wait smartly. Realize what changes after a successful upload, then wait for that element/message to appear. With Selenium 2 (WebDriver), this can be done very easily.
You can use
selenium.type("xpath of text box","path of your file")
OR for IDE
command=type
target=xpath_of_text_box
value=Path_of_your_file
example:
selenium.type("id=cvfile", "D:\\Automation\\resume.doc");

Firefox 3.5.2 Refresh(F5) causes Highlighted Form value to get copied to next field

I am having a strange issue in Firefox 3.5.2 with F5 refresh.
Basically, when I focus on an input field and hit f5 the contents of that input field gets copied to the next form field after the F5 refresh.
But, if you inspect the HTML source code, the values are correctly loaded.
I am not having this issue in IE8 or Safari 4.0.3.
The problem does not occur if I do a hard refresh or run window.location.refresh(true).
After F5 Refresh: http://i805.photobucket.com/albums/yy339/abepark/after.jpg
Here's an overview of what's going on.
I believe the thing you should look into is the autocomplete attribute,
you should set it to off on the input box. However be careful since this will trigger two effects.
When you refresh the page it won't remember the old values
The default dropdown of the already used values on that input box will also be disabled.
If you want to keep the second behavior you should set the autocomplete attribute back to on with JS.
Browsers can remember form field contents over a refresh. This can really throw your scripting off if it is relying on the initial value of a field matching what's in the HTML. You could try to prevent it by calling form.reset() at the start.
Different browsers have different strategies for detecting when a form or a field is the same as in the previous page. If you have clashing names, or names that change on reload, it is very possible to end up confusing them. Would have to see some code to work it out for sure.
In the backend, I am using ASP.NET MVC 1.0 with the Spark View engine. When I examine the source code after an F5 refresh in Firefox 3.5.2, the page renders correctly; however, if you look at the page visually the adjacent form field field gets populated with the value from the previous field.
I included enough code so you can just get an idea of what I'm trying to do.
Again, the rendering is fine and the final view/HTML code is fine. It's what I see on the screen that is incorrect. I am using hidden vars; but the issue occurred before using it as well.
Note in the code below, I have 2 distinct ID fields: "date_{projectTask.ProjectTaskId}" and "finishDate_{projectTask.ProjectTaskId}, which gets renders to something like "date_1" and "finishDate_2".
<table>
<for each="ProjectTask projectTask in projectTasksByProjectPhase">
<input type="hidden" value="${projectTask.ProjectTaskId}" />
<tr>
<td class="date">
<div class="box">
<div class="datefield">
<input type="text" id="date_${projectTask.ProjectTaskId}" value="${startDate}" /><button type="button" id="show_${projectTask.ProjectTaskId}" title="Show Calendar"><img src="~/Content/yui/assets/calbtn.gif" width="18" height="18" alt="Calendar" ></button>
</div>
</div>
</td>
<td>
<div class="box">
<div class="datefield">
<input type="text" id="finishDate_${projectTask.ProjectTaskId}" value="${finishDate}" /><button type="button" id="finishShow_${projectTask.ProjectTaskId}" title="Show Calendar"><img src="~/Content/yui/assets/calbtn.gif" width="18" height="18" alt="Calendar" ></button>
</div>
</div>
</td>
</tr>
</for>
</table>
FYI: ${} are used to output variables in the Spark View engine.
I am also using the YUI 2.7 Connection to make Ajax calls to update the datebase for "change" and "enter/tab key press" events. I am able to verify that the AJAX calls are made correctly and the form field values are still valid.
The problem occurs when I just do a F5 refresh; for some reason, the "finishDate_1" gets populated with the value from "date_1".
This problem occurs just by clicking on "date_1" and hitting F5; so, the adjacent field just gets populated even if there are no AJAX calls.
Here's the Javascript code I call towards the end of the body"
YAHOO.util.Event.onDOMReady(
function() {
var idList = YAHOO.util.Dom.getElementsBy(function (el) { return (el.type == 'hidden'); }, 'input');
len = idList.length;
var startDatePickers = new Array();
var finishDatePickers = new Array();
for (var i = 0; i < len; i++) {
var id = idList[i].value
startDatePickers[i] = new DatePicker("date_" + id, "show_" + id, "cal_" + id);
startDatePickers[i].valueChanged.subscribe(updateDate, 'S');
finishDatePickers[i] = new DatePicker("finishDate_" + id, "finishShow_" + id, "finishCal_" + id);
finishDatePickers[i].valueChanged.subscribe(updateDate, 'F');
}
}
}
The form field gets copied over before any Javascript code is processed because I call the Javascript code towards the end of the body after all HTML is rendered. So, I'm guessing it's a refresh issue in Firefox? What do you guys think?
As you can see above, I created my own calender date picker objects which allows you to either enter the date in the text manually or by clicking on a button to view the calendar and select a date. Once you enter or select the date, an AJAX call will be made to update the datebase in the back end.
Thanks everybody for the quick responses.
#Anonymous: whoever you are, you are awesome!
#bobince: thanks for the feedback as well.
I added a dummy form tag with the attribute autocomplete="off" and that solved the problem!
I was scratching my head because I didn't get this issue in Safari 4.0.3 or Internet Explorer 8.
<form action="" autcomplete="off">
<!-- my code -->
</form>
The values were loading correctly in the back end (ASP.NET MVC 1.0/Spark View engine) and the HTML source code reflected this, but the input field values were not getting populated correctly. I was using the YUI Connection Manager and Javascript to support edit-in-place and the date pickers.
I tried changing the XHR call to a GET call instead of POST and the same issue was happening.
Anyway, the problem was that the Firefox was not setting the correct values for the input fields for F5 refreshes.
Again, thanks so much! You guys rock!
All element id's must be unique, if two elements have same id's then that could be reason why Firefox inserts same values to elments that didn't orginally have those values entered.
I had a similar problem related to my question at Input control shows incorrect value, even 'though inspect element shows the right value is there
The problem occurred for me in Firefox, but not Chrome, for some but not all controls on the form, and when I pressed F5, but not ctrl-F5.
The "dummy form" seems to have resolved it for me.

Resources