Using a merged array in another function - javascript

Not sure exactly how to word this but hopefully you'll get my drift. I'm trying to use my If statement to merger the contents of my images array into another array, there is then a function that uses that array to do a picture slide show.
I feel that I should mention that this is a school assignment, so I'd like to not change the chgSlide function if I don't have too.
I think my problem is that when i have var myPix=[] it clears the merger. But i'm not sure really what the solution is, i've tried just doing myPix=redCarsPic but it didn't work.
Also, within the code i commented out that ways i had merged the array, i'm not sure if a certain approach is better than an other, i'm sort of partial to the jquery and would like to be able to keep that approach if i can.
Heres my script block:
function radioCheck(){
if (document.getElementById("redCars").checked){
//alert("red"); Array.prototype.push.apply(myPix,redCarsPic);
//alert("red"); myPix.push.apply(myPix, redCarsPic);
$.merge(myPix,redCarsPic)
alert(redCarsPic+" r2");
};
if (document.getElementById("blueCars").checked){
alert("blue"); myPix.push.apply(myPix, blueCarsPic);
};
if (document.getElementById("greenCars").checked){
alert("green"); myPix.push.apply(myPix, greenCarsPic);
};
}
var myPix=[];
thisPic=0;
imgCt=myPix.length-1;
alert(myPix+"mpixalt")
function chgSlide(direction){
if(document.images){
thisPic=thisPic+direction
if(thisPic>imgCt){
thisPic=0
}
if(thisPic<0){
thisPic-imgct
}
document.myPicture.src=myPix[thisPic]
}
}
var redCarsPic =["images/redCarsA.jpg","images/redCarsB.jpg","images/redCarsC.jpg","images/redCarsD.jpg","images/redCarsE.jpg"];
var blueCarsPic =["images/blueCarsA.jpg","images/blueCarsB.jpg","images/blueCarsC.jpg","images/blueCarsD.jpg","images/blueCarsE.jpg"];
var greenCarsPic =["images/greenCarsA.jpg","images/greenCarsB.jpg","images/greenCarsC.jpg","images/greenCarsD.jpg","images/greenCarsE.jpg"];
Heres the entire code if needed:
http://pastebin.com/YLtWFciE

When you press the submit button in your form, it tries to submit your form which causes the page to be reloaded, thus reinitializing all your state back to a new page which is an empty array.
You can stop the form from submitting either by changing the button to be just a normal button, not a submit button or by block the default action of the form submission.
The simplest change is to just change this:
<input type="submit" id="submitButton" value="Go!" onclick="radioCheck()"/>
to this:
<input type="button" id="submitButton" value="Go!" onclick="radioCheck()"/>
With no submit button, the form will not be submitted and the page will not reload.
Working demo: http://jsfiddle.net/jfriend00/4bx35hjy/
FYI, it is also possible to cancel the form submission in your radioCheck() function before it occurs, but since you never want to submit the form, it seems better to just not ever have a submit button in the first place.

Related

How exactly work this form submission JavaScript?

I am very new in JavaScript and I have the following doubt about how exactly work this script that submit a form:
So in my html I have the following form:
<form id="actionButton<%=salDettaglio.getCodice()%>" action="salwf.do?serv=1" method="post">
<button id="accept" name="ctrl" value="Accept" type="submit" class="acceptButton" onclick="sottometti(this,'<%=salDettaglio.getCodice()%>')">ACCEPT ICON BUTTON</button>
<button id="cancel" name="ctrl" value="Cancel" type="submit" class="cancelButton" onclick="sottometti(this)">CANCEL ICON BUTTON</button>
<button id="sap" name="ctrl" value="SAP" type="submit" class="sapButton" onclick="sottometti(this)">SAP ICON BUTTON</button>
<input id="testId<%=salDettaglio.getCodice()%>" name="test" type="hidden">
</form>
So the submission of this form is directed towards a page salwf.do and each time pass a parameter named serv and having 1 as value (is this a GET?)
Then inside the form I have 3 buttons having different id and different values and the input tag (that I think it is what I am submitting, is it right?)
As you can see when the user click on a button is called the sottometti(this) script that take as parameter the reference to the object that have generated the click (in this case the clicked button)
And this is this JavaScript code:
function sottometti(obj,id){
document.getElementById('testId'+id).value = obj.value;
document.getElementById('actionButton'+id).submit()
}
So how exactly work this script?
I think that it do the following thing (but I am not sure about it and maybe I am missing something).
It take 2 input parameters: the clicked button reference (obj) and the id string (that represent a code of a Java object, but this is not important now).
Using:
document.getElementById('testId'+id)
it retrieve the reference of the input tag of the form and set the value (what I want submit) with the button value (that can be: Accept or Cancel or Sap)
Then by:
document.getElementById('actionButton'+id)
retrieve my form and submit it
So the value of the clicked button will be submitted to the salwf.do servlet as POST.
Is it my reasoning correct or am I missing something?
Tnx
Yes your reasoning is correct, but you have some issues.
you only pass the ID from one of the buttons - the accept one
For all buttons you seem to want to add Accept/Cancel/SAP to a hidden field called testAccept, testCancel or testSAP and submit a form with ID actionButtonAccept, actionButtonCancel, actionButtonSAP but do not have either the field nor the form in the Cancel/SAP situation.
do not submit in a click event of a submit button
I would do
function sottometti(obj){
obj.form.test.value = obj.value;
// obj.form.submit(); // all the buttons are submit buttons
}
Be careful about one thing. Here you attach JavaScript to button[type=submit] and you execute form submit. So in fact you submit it twice.
If you want to prevent submission you should at least return false in your callback function (best is anyhow to use event.preventDefault();) like in that answer https://stackoverflow.com/a/23646215/2802756

on('submit' works when clicking the <button> but not when pressing enter on an input field

I'm using on('submit') to detect when the form was submitted, but it only works when the user clicks on the submit button.
I use a <button> tag so I can put an image inside the button. I know I could use an input with type="submit" and use CSS it with the image, but I'd like to know the alternative jQuery way.
I was thinking doing an or comparison, for example on('submit') OR when user presses enter on any of the input field, but how should I do that?
$('#form').on('submit', function (e) {
e.preventDefault();
var email = $('#email').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
});
<form id="form">
<input id="email" maxlength="64" name="EmailEDIT" type="text" width="100">
<button id="submitBtn"><img height="30" src="images/fx_demo_button.png" width="74"></button>
</form>
If the user presses enter in one of the field, the form will submit. It will trigger the same event as the button does. If this does not occur, something's up in your code.
You commented that your code doesnt work, but it does: http://jsfiddle.net/B5pZ4/
All I've added was alert(1); the rest is your code from this topic
You define your function in the eventhandler, might be better to seperate that, just in case you want to use that function again (or alter it a bit and use it in two situations).
If you seperate it in your code, it'll make more sense, I also think this is the problem you're having:
http://jsfiddle.net/B5pZ4/1/
You can actually make your code work with just one line. You create the function in your eventhandler (which, in this case, should be considered bad practice!), but you never call it. Either remove the function declaration, or add this under the function:
return validateEmail( email ); // THIS IS BAD PRACTICE AS FIX!
A tip: if you're working in html5, you can use this and the browser will do validating for you:
<input type="email" />
You need to insert an invisible input type submit for this to work.

KnockoutJS: Posting only visible form elements

I have just started using Knockout.js My form has elements which I call questions. I hide/show them based on user selections. When user hits the submit button I want to post only the visible questions at the time of submit. What I have is this:
// length of Results(questionArray) is 260
var vmToPost = viewModel;
delete vmToPost.__ko_mapping__;
ko.utils.arrayForEach(vmToPost.Results(), function (question) {
if (!(vmToPost.getQuestion(question.QuestionID()).visible())) {
ko.utils.arrayRemoveItem(vmToPost.Results(), question);
}
});
The util function arrayForEach is behaving strange. It loops through the array very differntly. I had to hit the submit button 7 times to get all the visible elements and come out of the util function. It doesnt throw any error message in the console or the fiddler.
What am I doing wrong. Please help.
Html contains a built-in way to skip items from being submitted. It's the disabled attribute, which can be controlled using Knockout with the enable or disable bindings.
<div data-bind="visible: visible">
<label>Name: <input name="name" data-bind="enable: visible"></label>
</div>

How can I change the form on clicking "Save", and then submit the final version of the form?

I have a form with a variable number of textboxes, and when I click Save (the submit button), I want it to remove the empty ones and then save the form without the empty boxes.
But it's only half-working. When I click Save, the empty boxes are visually removed. Moreover, usually there's a validation error when boxes are left empty, but with removeEmptyBoxes() there is no validation error so I know the boxes are somehow successfully removed before submit. But when the page refreshes, the empty boxes reappear. On the other hand, if I divide it into two buttons and use one button to removeEmptyBoxes() and then click the other button to Save, that works fine and the deleted boxes stay deleted.
I'm sure I can get round this in a completely different way, but it's frustrating that it doesn't work the way I want it to. Is there any way to do this?
My form is made using Ajax.BeginForm. My button looks like this:
<input name="xiSubmit" type="submit" value="Save" onclick="removeEmptyBoxes()" />
function removeEmptyBoxes() {
$('div.box').each(function () {
var content = $(this).find('.box-content').val();
if (content == '') {
removeElement(this);
}
});
return true;
}
solution: my removeElement() function consisted of a slideUp to hide the box nicely and then removing the box completely. I removed the slideUp bit and it all worked fine. Not sure why it didn't work with the slideUp.
For a form with id myForm:
$('#myForm').submit(function(ev){
ev.preventDefault(); // prevent the original form submit
// do your thang
$(this).submit(); // submit form with your changes
});
Given this simple form:
<form id="theForm" method="post">
<div class="box">
<div class="box-content">
Test
</div>
</div>
<input name="xiSubmit" type="submit" value="Save" />
</form>
You can add javascript like this:
$(function() {
$("#theForm").submit(function() {
$('.box-content',$('div.box')).remove();
});
});​
The above submit handler is executed before the form is actually submitted, so you can do any pre-processing you'd like.
Here's a JSFiddle you can play around with: http://jsfiddle.net/cTwMW/. Notice I added return false at the end of the fiddle javascript so the form doesn't submit (allowing you to see the jquery remove the element).

Adding submit event on form prevents submit parameter from being included in HTTP POST

Just what the question title says. I'm using SpringMVC, but that's irrelevant really. I just need to be able to pass the submit button name=value along with the rest of the form parameters for validation and control purposes. Example below for clarification:
The HTML I'm using:
<form action='somepage.htm' method='post'>
<input name='somename' value='bob' />
<input type='submit' name='mybutton' value='click me' />
</form>
The JavaScript (with jQuery) I'm using:
$('form').submit(function() {
$('input[type="submit"]', this).attr('disabled','disabled');
return true;
}
And so the HTTP POST request looks like this without the JavaScript event binding:
somepage.htm?somename=bob&mybutton=click%20me
And with the bound event, it excludes the button parameter as such:
somepage.htm?somename=bob
I need to be able to disable the buttons and still send the button value to the server for processing.
Thanks!
SOLUTION:
The code I actually used to solve this problem is:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var clone = $(this).clone();
$(clone).attr("type","hidden");
$(this).attr('disabled','disabled');
$(clone).appendTo($(this).parents('form')[0]);
return true;
});
});
And in case anyone was wondering, pressing Enter on a field in the form does in fact trigger the click event on the first submit button in the form!
Disabled inputs cannot be submitted.
http://www.w3.org/TR/html4/interact/forms.html#h-17.12
So maybe the way to go is to add a hidden element <input type='hidden' value='foo' name='bar'/> to stimulate the validation methods on the other end.
I think, if the submit button is clicked, then it's values will also be submitted, like rest of the form.

Categories