How to get what radio button was clicked in Meteor - javascript

I am completely new to Meteor and I'm trying to build a simple app. I currently have a form with 4 radio options and a submit button. When users click the submit button and I want to know which radio option they selected. I have no idea how to get started though. Can anyone help me? Below is my html and javascript code, respectively:
<form class="form-horizontal well mystery-form">
<fieldset class="col-md-offset-1">
<h2>{{question}}</h2>
<br>
<div class="form-group">
<div class="col-md-10 mystery-form">
{{#each answers}}
<div class="radio">
<label>
<input type="radio" name="mysteryForm" checked=""
style="margin-bottom: 0; margin-top: 0;">
{{answer}}
</label>
</div>
{{/each}}
<br>
<button type="reset" class="btn btn-default">Back</button>
<!-- Hide this when the answer is correct -->
<button type="submit" class="btn btn-primary">Check Answer</button>
<!-- Show only if the answer is correct -->
<button class="btn btn-primary">Next</button>
</div>
</div>
</fieldset>
</form>
JS:
Template.mystery.events({
"submit .mystery-form": function(event) {
// no idea what to do here
}
});

Semantics
You'll probably want to remove the whole wrapping .radio element. It's unnecessary. Try using as few elements as possible. It performs better and makes debugging easier.
Retrieving the checked input
The event object passed to an event-map callback has a property target. In your case that is .mystery-form. So you can use a simple jQuery selector to find the checked element:
$('input[name="mysteryForm"]:checked', event.target)
This will get you the checked value with the name mysteryForm. This was quiet straight forward. The problem is retrieving the value. Doing that would get sort of messy. So I'd just pass it to the element as a data- attribute:
<input type="radio" name="mysteryForm" checked="" style="margin-bottom: 0; margin-top: 0;" data-answer="{{ answer }}" >
Now you can simply do this:
$('input[name="mysteryForm"]:checked', event.target).data('answer')

First, you may want to prevent the normal form submission and avoid a page reload. As you are building a single page application you will want to do the form submission logic by yourself. Also, reloading the page by form submission does not make any sense in such application.
Secondly, you have to actually gather the data, and then do what you want with these data.
Put it all together and you get something like this:
Template.mystery.events({
"submit .mystery-form": function(event, template) {
//1. prevent default behavior (form submission)
event.preventDefault();
//2. get your data
//either by name (HTML name attribute)
var inputValue = template.mysteryForm.value;
//or by id (HTML id attribute)
var inputValue = template.find('#myId').value;
//3. Do whatever you want (method call for example?)
Meteor.call('myMethod', inputValue, function(error, result) {
//wait for the call result...
});
}
});

Related

How to remove user input from a text input box with Jquery on submit?

I can't seem to get this to work for the life of me. I've tried setting the value to '' with getElementById('guess').value and $('#guess').val, tried using $('#formGuess').reset(), etc. Don't know why the value won't clear out.
Here is my code on this:
js
$('#submit').on('click', function(e) {
e.preventDefault();
var guess = $('#guess').val();
$('#guess').removeAttr('value');
}
HTML
<div class="container center">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form class="form-horizontal" method="post" id="guessForm">
<div class="form-group">
<div>
<input type="text" class="form-control" placeholder="Guess" id="guess"/>
</div>
<input type="submit" class="btn btn-success" name="submit" value="Guess" id="submit"/>
</div>
</form>
</div>
</div>
Set empty string as the value of textbox like following.
$('#guess').val('');
First, you should attach a "submit" listener to the form, not to the button, e.g.
<form id="someForm"></form>
$("#someForm").submit(function () {
// your code
});
But if you want to attach it to the button, then you can do that, no worries.
Make sure that the event is called. Are you sure that the function within "click" event is called? Put there a console.log("someText");
If it's called, then make sure that jQuery is getting the right element. Maybe you've made a typo? Maybe there's a missing "#" sign? Or maybe the jQuery is not loaded at all?
Open developers tools and check what's in the console.
Probably you've made a simple mistake - it's always about simple mistakes. : )
From your code,
var guess = $('#guess').val();
you are getting the value not setting.
To set the value
$('#guess').val('');

Hide/Show form in HTML produce unusual result

I've been trying for some time now (some time = whole day) to figure out why I have this strange problem with my form. I have a client who wants a stand-alone HTML page running locally which would display one form with couple of textbox and one button. After info is entered and user click that button, a second form should show up with new textboxes. Form can't have a redirection to another website or file. It all has to be in that (HTML) file.
I figured out this would be easiest to do with jQuery but loading whole library just to hide one form is plain stupid. So I take a look at other option and decided to use pure Javascript.
The problem is when I click "NEXT" first time the 1st form disappear but then apear a second later like some sort of request is sent. Bellow is the code I currently have. I tried making an JSFiddle but browser blocks every time I access it.
Javascript:
function hideAll() {
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
showFirstForm();
}
function showFirstForm() {
if (document.getElementById('second').style.display == 'block') {
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
}
}
function showSecondForm() {
if (document.getElementById('first').style.display == 'block')
{
document.getElementById('second').style.display = 'block';
document.getElementById('first').style.display = 'none';
}
}
HTML:
<body class="if5" onload="hideAll()"> // I'm loading hideAll() on refresh to hide second form
....
<!-- FORM 2 -->
<form id="first" action="#" class='tx_anmelden' method="post" autocomplete="off" >
<filedset>
<label for="name"> Your name </label>
<input name="name" value="MyName" /></input>
<button onClick="showFirstForm()">Next</button>
</filedset>
</form>
<!-- FORM 1 -->
<form id="second" class='tx_anmelden'>
<fieldset>
<label for="name"> Your name </label>
<input name="name" value="MyNaffffffme" /></input>
<button onClick="showSecondForm()">Next</button>
</fieldset>
</form>
....
References:
getElementByID
Besides the fact that you have your form id's switched, <button> has a default type of submit. So when your button is clicked it is posting the form to #. So correct your form ids, and then change your button code type to button:
<button type="button" onClick="showSecondForm()">Next</button>
Here are some docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
Here is a working jsfiddle using the corrected code: http://jsfiddle.net/789SP/
First off, any button in a form that doesn't have a type attribute or has a type attribute of submit will by default submit the form on click.
Second, it looks like you are trying to implement some sort of wizard. If this is true you don't want each part to be it's own form because at the end you're going to want to send all of this data to the server which won't work if it's in two forms.
The entire thing needs to be in one form with sections inside that you show/hide. To navigate between the sections you'll want to use
<button type="button" onClick="showSecondForm()">Next</button>
To do wizards is always a pain in the butt. Once you start handling validation you need to figure out which step has an error in it and show that section, or if the user uses the back button they might expect the form to go back to step one. You might want to search for a third party solution that provides some of the boiler plate functionality. These might help
This should get you off to a good start though.
Edit
Don't attempt this from scratch. Use this
<!-- FORM 2 -->
<form id="first" action="#" class='tx_anmelden' method="post" autocomplete="off" >
<fieldset> **fieldset was misspelled as "filedset"**
<label for="name"> Your name </label>
<input name="name" value="MyName"></input> **your input had /> at it's end, which is unfortunately wrong**
<button onClick="showFirstForm()">Next</button>
</fieldset> **fieldset was misspelled as "filedset"**
</form>
<!-- FORM 1 -->
<form id="second" class='tx_anmelden'>
<fieldset>
<label for="name"> Your name </label>
<input name="name" value="MyNaffffffme"></input> **your input again had /> at it's end, which is unfortunately wrong**
<button onClick="showSecondForm()">Next</button>
</fieldset>
</form>

How to remove/enhance/change the form submit data using standard submit event and jquery, before the actual submit happens?

Is it possible to extract data from a form, say:
<form action="/search/search" data-remote="true" data-type="json" id="search_form" method="get">
<div class="input-group">
<span class="input-group-addon">
<input name="search[req][text][e]" type="hidden" value="false">
<input id="search_req_text_e" name="search[req][text][e]" type="checkbox" value="true">
</span>
<input id="search_req_text_v" name="search[req][text][v]" type="text" value="">
</div>
<button id="fire_search" type="submit">Search</button>
</form>
I thought about jQuery's .submit() method. But how to extract and change the url from the event?
$('#search_flickr_panel_body form').submit(function(e) {
console.log(e)
}
I don't see in Chrome DevTools any url in the printed event object
I would like to remove the text fields which are unchecked.
Maybe .attr('disabled', 'true') would be a variant for remove, but how to change the data, without change it in the text field, only in submit url?
Update:
I have over 100 such input fields in the form, so to just send all of them even if only one is checked is not so nice (too much useless data making the communication overhead)
Update2:
I want not only be able to remove the unchecked data from the submit data, but also be able to change this data before submit(e.g. add a prefix to the values, add new parameters), so that I can effect the resulted url (with data).
This will disable all the text fields that have associated checkboxes unticked...
$(function() {
$('#search_form').submit(function(e) {
e.preventDefault();
$(".input-group").each(function() {
$(this).find("input:text").prop("disabled", !$(this).find("input:checkbox")[0].checked);
});
this.submit();
$(".input-group input:text").prop("disabled", false);
}
});
The disabled ones should not be submitted with the rest of the form.

html form trying to http get when a button is pressed

Ive got a html form with a few select lists and a text box in it. I also have a submit button which is outside of the form. The reason for this is I want to construct the parameters myself, as I dont want the content of all of the select lists. The problem I am having is, that when I press my submit button,The form automaticly trys to redirect to the same page, but with a ? at the end with all the contents of the form. I am also having problems where window.location.href is not working inside the submit() javascript method, but I am not sure if this is caused by the form issue or not. Example code:
<form>
<input name="cName" type="text" class="input-xlarge" id="input01" placeholder=
"Enter title" />
<div class="control-group">
<hr />
<label class="control-label" for="select01">Select box 1</label>
<div class="controls">
<select id="select01" name="type" onChange="reportModification(this.value)">
<option>One</option>
</select>
</div>
</div>
</form>
<button class="btn btn-primary" onClick="next()">Next</button>
This is not the exact code from the page, just a replica.So it might not be valid html in some places. Thanks for the help :)
The reason you get parameters in the url is that a get request is used instead of a post request. you should use:
<form method="POST" action="">
Also why is your button outside the form? you could have this instead:
</div>
<input class="btn btn-primary" type="submit" value="Next" onClick="next()" />
</form>
I think your button has to be inside the form element. You could use an onsubmit in the form element to intercept the form before it gets sent to the server. Here you could manipulate the values before they go. You would also need an action attribute in the form. If your function returns true, the data will be submitted, false and it won't.

How to manually trigger AngularJS validation from a button outside of the form tags?

Given this code:
<div ng-controller="MyCtrl">
<form ng-submit="onSubmitted()">
Header inputs:
<input type="name" ng-model="sample" required/>
<input type="name" ng-model="sampleX" required/>
<input type="submit" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>
</form>
<hr/>
Some other form here. Think line items
<hr />
<a class="btn" ng-click="/* what could should be put here, so this can trigger the firt form's validation, then submit? */">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>
</div>
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.onSubmitted = function() {
alert('submitted!');
};
}
I want the last button to trigger the validation(then submit when things are valid) on first form. As of now, only the button inside the form can trigger that form's validation and submission. Is there any possible way for a button outside the form to do that?
Live test: http://jsfiddle.net/dzjV4/1/
You can create directive which you can then attach to <a class="btn".... Check this jsfiddle
http://jsfiddle.net/dzjV4/2/
Note that I added to <input type='submit' id='clickMe'... and linked it with link at the bottom <a class='btn' linked="clickMe"...
for (control of $scope.[form name].$$controls) {
control.$setDirty();
control.$validate();
}
You can try the above codes. Make it running before submit.
Ideally there'd be a programmatic way to cause validation to re-run across a form. I have not investigated that completely but had a situation that required multiple controls to be re-validated based on different data in the scope -- without the user interacting with the individual controls. This arose because the form had two action buttons which each required different validation rules be in play when they were clicked.
The UI requirement changed before I fully implemented forcing re-validation but before it did I got most of what I needed by copying and then re-setting the form's data. This forced re-validation across the form within the current scope. Basically, it's along the lines of the following (not tested, but taken from the code that was working). In this case the form's data was bound to the properties in one object.
var formData = $parse(<form's model>);
var dataCopy = angular.copy( formData($scope) );
formData.assign( $scope, dataCopy );
This may or may not be acceptable, but if you can get away with the SUBMIT button being disabled until the form is completed, you can do this:
<form name="formName">
<input ng-required="true" />
</form>
<button ng-click="someFunction()" ng-disabled="formName.$invalid" />
It's also worth noting that this works in IE9 (if you're worried about that).
Give your form a name:
<div ng-controller="MyCtrl">
<form name="myForm">
<input name="myInput" />
</form>
</div>
So you can access your form validation status on your scope.
app.controller('MyCtrl', function($scope) {
$scope.myForm.$valid // form valid or not
$scope.myForm.myInput // input valid or not
// do something with myForm, e.g. display a message manually
})
angular doc
There is no way to trigger browser form behavior outside of a form. You have to do this manually.
Since my form fields only show validation messages if a field is invalid, and has been touched by the user:
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}

Categories

Resources