AngularJS directive for "html select required" - javascript

Another day with another question. I'm working again on my web application. Now I got a problem. THe 'required' attribute is not supported in major browsers
(http://www.w3schools.com/tags/att_select_required.asp)
, it only works if the first option value is empty. Well that works fine, the submit event does nothing if the form is $invalid and it is when it's left by "Please select".
Land*:<br />
<select id="countries" name="country" data-ng-model="contact.country" required required-select>
<option value="">Please select</option>
<script type="text/javascript">
$(document).ready(function () {
var countries = {};
if (countries.length > 0) {
return countries;
} else {
$.get('WebKalkTool/country_de.xml', function(data) {
countries = data;
var that = $('#countries');
$('name', countries).each(function() {
$('<option />', {
text: $(this).text(),
}).appendTo(that);
});
}, 'xml');
}
});
</script>
</select>
<span class="error" data-ng-show="mandatory">Please select an item</span>
</p>
What I'm searching is a directive which checks if the value is empty, and then shows
the error after submit and if they select an item, the error vanishes.
Now the directive should maybe look something like this:
authApp.directive('requiredSelect', function () {
return {
require: 'select',
link: function (scope, formElement, attr, formSelect) {
console.log('FORM : Linker called');
console.log(formSelect);
console.log(formSelect.selected.value); // is undefined..
scope.$watch(formSelect.selectedIndex.value, function () {
console.log("index changed"); // Always log when another index is selected
if (formSelect.selectedIndex.value == "") {
console.log("value="");
// only show error after submit OR has visited on span id mandatory (or add new template?
// Tell the form, it's invalid, select is invalid
} else if (formSelect.selectedIndex.value != "") {
console.log("index > 0");
// everything is fine, select is valid
} else {
console.log("FORMSELECT.SELECTINDEX = UNDEFINED");
// just 4 testing my link
}
});
}
};
});
I took out the HTML5 validation because of compatibility thoughts and HTML5 validation shows only the first hint anyway.
It should be something equals like 'required' attribute for input fields and work the same way, I don't want to make my submit button disabled. Maybe I also can remove this "Please Select" option and leave it empty.
Or maybe I'm just not that clever enough to do something equal like:
<span class="error" data-ng-show="requestForm.place.hasVisited && requestForm.place.$invalid">Required!</span>
Doesn't matter if we check the value or the selectedIndex, whatever.
Thanks for your help and regards
Anthrax

AngularJs already know how to treat the required attribute (see here). In your case you might want to do something similar to that :
<form name="myForm">
<select name="country"
ng-model="country"
ng-options="c.name for c in countries"
required>
<option value="">-- chose country --</option>
</select>
</form>
Then up to you to display an error message when your form and/or select is marked as invalid by Angular or after a click on the submit button.
// Inline validation appears directly when select value is empty
<span class="error" ng-show="myForm.country.$error.required">Required!</span>
// Or after a click on submit, assuming you have set a boolean to show/hide error
<span class="error" ng-show="validationFailed">Required!</span>
I have assembled a working example with the 2 possibilities here.

Related

Disable button in jQuery until all required fields have values (specifically with select)

At the moment I have the following form:
<table>
<tr><td class="labelTD"><label for="manifestNumber">Manifest No.:</label></td><td class="detailsTD"><input type="text" class="form-control" placeholder="Manifest Number" name="manifestNumber" id="manifestNumber" required></td><td><span class="requiredInput">*</span></td></tr>
<tr><td class="labelTD"><label for="claimOrigin">Carrier Origin:</label></td><td class="detailsTD"><select id="claimOrigin" class="form-control" required name="claimOrigin">
<option></option>
#foreach($origins as $origin)
<option value="{{ $origin->id }}">{{ $origin->customer_name }}</option>
#endforeach
</select></td><td><span class="requiredInput">*</span></td></tr>
<tr><td class="labelTD"><label for="originTerminal">Origin Terminal:</label></td><td class="detailsTD"><select class="form-control" required><option selected value="">Please Select</option><option value="CINC-Cincinatti">CINC-Cincinatti</option></select></td><td><span class="requiredInput">*</span></td></tr>
<tr><td class="labelTD"><label for="date">Date Unloaded:</label></td><td class="detailsTD"><input type="date" name="claimDate" id="claimDate" class="form-control" required></td><td><span class="requiredInput">*</span></td></tr>
</table>
With this button at the end:
<button id="createManifestButton" class="btn btn-primary">Create New Manifest</button>
Now I've been trying to use others' examples but the script is refusing to work for me, namely the select option.
At the moment, I'm using this jsfiddle: http://jsfiddle.net/qKG5F/3370/ which is based on the answers from this question: Disabling submit button until all fields have values
Unfortunately, in the comments, no one ever responded to the questions about other uses (like radio buttons, checkboxes), but the select issue was never responded to. So is there anything I can do? I want to disable the button specifically because it runs an AJAX script and for the sake of the average user, I just want to disable the button until all fields, including the select are filled out.
(function() {
$('.manifestSubmit').change(function(){
$('.manifestSubmit').each(function(idx, elm){
if (elm.value == 'Please Choose' || elm.value.length == 0) {
$('#register').attr('disabled', 'disabled');
return false;
}
if ((idx+1) == $('.manifestSubmit').length)
$('#register').removeAttr('disabled');
});
});
})()
You can do what says "Rasmus Stougaard" with the option tag and avoid the condition (elm.value == 'Please Choose' || )
Based on the previous jsfiddle you linked, I forked and altered to code to work with your form. See here: http://jsfiddle.net/xrc35p7b/6/
(function() {
$('.form-required').change(function() {
var empty = false;
$('.form-required').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#createManifestButton').attr('disabled', 'disabled');
} else {
$('#createManifestButton').removeAttr('disabled');
}
});
})()
All form fields (of any type) with the class "form-required" will need to have a non-blank value in order to enable the button.
In your example the select "blank" option should have the value "" like this:
<option value="">Please Choose</option>
Check this updated fiddle http://jsfiddle.net/qKG5F/3380/

How do I get jquery validation errors to display on a bootstrap-combobox?

I've been using this very cool bootstrap-combobox from here: https://github.com/danielfarrell/bootstrap-combobox
I currently have a .NET MVC 5 project which is using its out of the box validation (jquery unobstrusive validation), and any validation errors do not show up with the combobox control. My question is similar to the one here (unfortunately it has no answers): boostrap combobox validation - is it possible?
I took some time to create a jsfiddle for it: http://jsfiddle.net/1doe359f/3/
HTML:
<form id="experiment" action="/" method="post">
<div class="form-group">
<label class="control-label" for="PersonID">Person</label>
<select class="form-control combobox" data-val="true" data-val-required="This field is required." id="PersonID" name="PersonID">
<option value=""></option>
<option value="5">Bruce Banner</option>
<option value="9">Bugs Bunny</option>
<option value="8">Daffy Duck</option>
<option value="10">Elmer Fudd</option>
<option value="6">Jean Grey</option>
<option value="4">Clark Kent</option>
<option value="3">Peter Parker</option>
<option value="7">Scott Summers</option>
</select> <span class="field-validation-valid" data-valmsg-for="PersonID" data-valmsg-replace="true"></span>
</div>
<p>
<button type="submit" value="Save" role="button" class="btn btn-default" aria-disabled="false">Save</button>
</p>
Javascript:
var validator = {};
$(document).ready(function () {
$('.combobox').combobox();
var $form = $("#experiment");
// prevent form submission
$form.submit(function (e) {
e.preventDefault();
return false;
});
validator = $form.validate();
});
If you remove "combobox" from the control's class and hit the save button, you can see the error message pop up, as it should. It does not show up when the control is a combobox, however.
How can I get the validator errors to display while using this combobox control?
Usually I can stumble through this kind of thing, but this has a few too many moving parts for a javascript novice like myself. Any help would be appreciated!
I have used errorPlacement within that validate function to handle controls that are particularly whiny.
errorPlacement: function (error, element) {
// Set positioning based on the elements position in the form
var elem = $(element);
// Check we have a valid error message
if (!error.is(':empty')) {
if (elem.is(':combobox')){...logic here}
There have also been controls that I have used that have a container around them, that causes the error to be hidden instead of showing up on the container.
I did get this working eventually, but it's not a pretty solution. I made this change in the bootstrap-combobox code:
/* COMBOBOX PLUGIN DEFINITION
* =========================== */
$.fn.combobox = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('combobox')
, options = typeof option == 'object' && option;
if (!data) { $this.data('combobox', (data = new Combobox(this, options))); }
if (typeof option == 'string') { data[option](); }
/* Added stuff to get jquery validation working */
data.$element.attr("name", data.$source.attr("id"));
data.$element.attr("data-val", data.$source.attr("data-val"));
data.$element.attr("data-val-required", data.$source.attr("data-val-required"));
data.$element.closest("form").removeData("validator").removeData("unobstrusiveValidation");
$.validator.unobtrusive.parse(data.$element.closest("form"));
});
};
The gyst here is that I copy the relevant attributes (name, data-val, data-val-required) from the original dropdown ($source) to the combobox control ($element), and then I reset the validator so that it recognizes this newly-made control.
FYI: This is not a great approach because it creates a dependency to jquery validator in the bootstrap-combobox, and it is inflexible (will only do a 'required' check). One reason I took this shortcut was that the control that is generated doesn't have any good identifiers, so it was much easier to use this banked reference.
It does work though, and if you're only doing 'required' checks on your combobox and only using jquery validation in your project, it is adequate. Hopefully it at least gives some insight to save someone time in the future.

jQuery merging select field and text input values in real time to another text field

I have a three field form. I'd like the third field (text box) to display a combination of the first two fields ... one being a select field and the other being a text field; these values separated with a space. I have tried the following with little success.
<form>
<select name="val1" id="val1">
<option value="">Select a value</option>
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input name="val2" id="val2" />
<input name="val3" id="val3" />
</form>
<script>
$('#val1, #val2').keyup(function(){ $('#val3').val($('#val1').val()+' '+$('#val2').val()); });
<script>
What I'm expecting is when a user selects an option from the select field, is value would appear in the third form field and when a user types something in the second field, its value would also appear in the third field separated with a space. This would all happen in real time. Oddly enough, the jQuery code does nothing in all browsers.
Maybe something to do with the keyup() function as a select field is using the mouse only. But even if I ignore the select field and type something in the second field, it should appear in the third field alone, but it doesn't.
Your #val1 is a select element, the keyup event can't be called with that.
Instead, you neeed to use change event.
$('#val1').change(function () {
changeThird();
});
$('#val2').keyup(function () {
changeThird();
});
function changeThird() {
$('#val3').val($('#val1').val() + ' ' + $('#val2').val());
}
JsFiddle: http://jsfiddle.net/ghorg12110/e7ru9jao/
For asp:TextBox, you need to use .attr() if you want to get the data generated:
$('#val1').change(function () {
changeThird();
});
$('#val2').keyup(function () {
changeThird();
});
function changeThird() {
$('#val3').attr("value", $('#val1').val() + ' ' + $('#val2').val());
}

Select Drop down Form Validation (Display text)

I am trying to validate a form.
What I am trying to do is validate the form by validating the Option display text not the option value, since the option values are int
Example:
<option value="selectcard">Please select</option>
If user clicks submit the form should validate if the option display says Please Select
regardless of what the option value is.
Code which is not working
function fun(){
$('#cardtype').change(function () {
var sel = $('option:selected', this).text();
if (sel == "Please select") {
$('.showotherpDescription').show();
} else {
}
});
}
Not working: http://jsfiddle.net/f5hxpo7g/2/
Also including the regular working example for validating the form based on option value
Validates Based on option value http://jsfiddle.net/f5hxpo7g/1/
Please let me know what i am doing wrong.
Thanks in advance.
Your function should be like this:
function fun()
{
var ddl = document.getElementById("cardtype");
var valor = ddl.options[ddl.selectedIndex].text;
if (valor == "--- Please select ---")
{
alert("Please select a card type");
}
}
Working fiddle:http://jsfiddle.net/robertrozas/XFtBD/169/
I fixed it, you should use this JS:
$(function () {
$('#subbutton').click(function () {
if ($('#cardtype option:selected').text() === "Please select")
{
alert("PLEASE SELECT");
}
});
});
And remove onclick="..." from the button, you don't need it. Also add id="subbutton.
Here's the working JSFiddle.
I checked out the jsfiddle you referenced and modified it slightly to make it work, you can see it here.
The issue with the code you provided is, IMO:
An issue with the purpose of your function (validation) and the event you're subscribing the code to (the combo selection changed event)
The way you're obtaining the text from the currently selected option, you should create the selector based on the element that contains the options, otherwise, if you have more than 1 combo in your page, you will get lots of values (one for each selected option).
Check out the code in the jsfiddle i provided and let me know if you need more information.
For reference, here is the code i used:
HTML:
<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select>
<input type="button" onclick="fun()" value="click here">
JS:
function fun(){
var cmb = document.getElementById('cardtype');
var sel = cmb.options[cmb.selectedIndex].text;
if (sel == "--- Please select ---") {
alert('Please select a different option');
//$('.showotherpDescription').show();
} else {
}
}
}

Check in javascript in the select

How can i check the select items in javascript / jQuery.
I want check in javascript. When you clicked on value limburg and brabant. But how can i select in javascript this options?
I have this code:
<form action="/" method="post" class="clearfix">
<fieldset class="clearfix">
<div class="field">
<select>
<option value="" selected="selected">Kies een regio?</option>
<option value="Limburg">Limburg</option>
<option value="Brabant">Brabant</option>
</select>
</div><!-- /field -->
</fieldset>
</form>
You'll want to bind the change event to the select box and put your filtering in there, it would be best to assign an id or class to the select element so it can be specifically selected but the following code should alert to the screen when either of these options are selected.
$(".field select").change(function() {
if($(this).val() === "Brabant") {
//Brabant was selected
alert("Brabant");
}
if($(this).val() === "Limburg") {
//Limburg was selected
alert("Limburg");
}
});
If you just want to know what the current value of the selected element to you can do
var selecteditem = $("select").val();
if(selecteditem === "Limburg" || selecteditem === "Brabant") {
alert("'Limburg' or 'Brabant'");
}
However this will not automatically trigger anything when the value is changed, to do that, this could be for validation purposes that you would do this to check that it is one of the two.
Assuming I've understood you correctly, you want to check the value of the selected option. You can do that by simply checking the value of the select element. With jQuery, that's as simple as:
$("select").val();
You probably want to bind an event handler to the change event so you can check the value when it changes:
$("select").change(function() {
if(this.value === "Limburg") {
//Limburg was selected
}
});
Here's a working example of that.
Not sure if i understood your question, but to change the selected value, you can do something like
$('select').val('Limburg'); // to select limburg

Categories