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>
Related
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.
I am trying to find a simple solution to a required input type of scenario. I have multiple small forms that all send on one button save on the bottom of the page. What I am trying to accomplish is something like ngRequired, however across the whole controller, not just the individual forms. So the desired effect is pretty simple - if any of the inputs aren't filled out - set a boolean( or something) to false that disables the save button at the bottom.
So my first attempt is like this -
I have a model on each of the required items - there are 10 items
then I have a function that checks when you try to click the button how many are chcked like this
if($scope.modeltracker1){
//if there is anything inside model 1 add 1 to the tracker
$scope.modeltracker += 1;
}
and if the counter is not 10, don't do anything (all required are not filled out)
if($scope.modeltracker != 10){
//do nothing because all required are not filed out
}else{
//run save, all required all filed out
}
So - I feel like there should be a much easier solution than my first attempt here. Maybe something along the lines of checking if any individual one of these required fields is false, don't fire? I know that ngRequied would be great for this, but unfortunately the way this has to be structured, it cannot be one large form. There has to be a much easier way to accomplish this task with angular.
Any input would be much appreciated, thanks for reading!!
You can use ng-form to nest your multiple forms. It allows using nested forms and validating multiple forms as one form.
So, you need to nest your multiple forms in one root form.
<div ng-controller="demoController">
<form name="parentForm">
<ng-form name="firstForm">
<input type="text" ng-model="firstModel" required>
</ng-form>
<ng-form name="secondForm">
<input type="text" ng-model="secondModel" required>
</ng-form>
</form>
</div>
Then, all you need to do is to check parent form's validation status.
angular.module('formDemo', [])
.controller('demoController', ['$scope', function($scope) {
if($scope.parentForm.$valid) {
//run save, all required all filed out
} else {
//do nothing because all required are not filed out
}
}]);
you can use myForm.$invalid directive, as explained here: Disable submit button when form invalid with AngularJS
My ultimate goal is to add some validation to a set of date fields. However, my javascript sucks, so I'm starting small.
I am starting out by trying to get an alert message when a user leaves a field.
(For simplicity I'm just doing it all in my view...) Heres what I go to work...
# html.erb-template
<div class="from_date">
From Date
<input type="text" id="from_date" name="from_date"></input>
</div>
<script>
$("#from_date").blur( function() {
alert("boom!");
});
</script>
Your code seems to be fine - problem is that class and id are named the same, but you want to watch the input field not the surrounding div.
I just made a fiddle from your script and changed
the listener to be attached to the input field's id - and it's working.
the alert into a console.log
see
$("#from_date").blur(function() {.....
// instead of
$(".from_date").blur(function() {.....
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).
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}