jQuery: Prevent Select List from turning green on select - javascript

This is probably pretty strange but I have a form page with various elements that are being checked for validation when I hit submit. Unfortunately I also have a management side of the page that performs its own Ajax actions.
One of these items has a select list that when I select an option it turns green. I don't really need/want the green validation on this select list as it isn't tied to my postback action at all.
Any ideas on how to turn it off with jQuery? (I'm currently just using $("#form").validate({ ... ...}) to validate my other fields and I think it is taking over for this element too)
Current Validation:
$(function () {
// Validation
$("#edit-opp-prod-form").validate({
// Rules for form validation
rules: {
Opportunity: {
required: true
},
CommissionAmount: {
required: true,
currency: ["", false]
}
},
// Messages for form validation
messages: {
Opportunity: {
required: "An Opportunity name is required."
},
ComissionAmount: {
required: "A Commission Amount must be set."
}
},
// Do not change code below
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
The Select List I don't want to be validated,
<section class="col col-5">
<div>
#Html.Label("ProductID", "Products", new { #class = "label" })
#Html.Action("ProductSelectList", "Products", new { unmappedProducts = true})
</div>
</section>
This produces this when I inspect,
<select id=ProductID" name="ProductID">Products</label>
<option value="...">...</option>
...
<option value="...">...</option>
</select>

Related

How do I find a radio button by value to check it with another element - VueJS

I apologize for the title being a little hard to understand. I had a hard time explaining it in one line. But here's what I'm trying to do.
I'm developing a screen within my app that supports a barcode gun reader. Barcode guns can only interact with textfields. And then through a text field(hidden) I can pass a custom barcode that instructs the UI to do something. Here is the UI explanation for clarity:
I have a radio button group with 2 options (yes and no)
I have a hidden textfield to accept the barcode gun read
I have a barcode for "yes" and another for "no"
If I scan the "yes" barcode, the radio button option with value = "Yes", should be checked
If I scan the "no" barcode, the radio button option with value = "No", should be checked
I initially thought that by changing the v-model to the correct value, it will do it, but it didn't check it. Likewise, by changing the v-model.value to true or false it will check to its appropriate value. But no cigar.
My idea on how this would work is by (pseudocode)
if querySelector with name ragrouphidden.value = "Yes" then find the option whose value is Yes and option.checked = true
else if querySelector with name ragrouphidden.value = "No" then find the option whose value is No and option.checked = true
The "find" part is what eludes me, or maybe there is an easier way.
Here's some relevant code
Template
<div>
<q-input
class="hidden-field"
v-model="ragrouphidden"
name="ragrouphidden"
#change="raSelectOption()">
</q-input>
<div>
<label class="col-6 text-weight-medium">Mark for Remote Adjudication</label>
<div>
<q-option-group
v-model="ragroup"
:options="raoptions"
#check="raRules($event.target.value)"/>
</div>
</div>
</div>
Script
data() {
return {
ragrouphidden: "",
ragroup: null,
raoptions: [
{
label: "Yes",
value: true
},
{
label: "No",
value: false
}
],
}
},
methods: {
raSelectOption() {
setTimeout(() => {
let hasFocus = document.querySelector("input[name=ragrouphidden]");
hasFocus.focus();
}, 500);
if (
document.querySelector("input[name=ragrouphidden]").value === "*yes*"
) {
this.ragroup.value = true; //this is what I need
} else if (
document.querySelector("input[name=ragrouphidden]").value === "*no*"
) {
this.ragroup.value = false; //This as well
}
},
}
Hopefully it makes sense to you guys. Thanks in advance.
You don't need to use ragroup.value to set the model value here. You can simply do this.ragroup = true; and vue will automatically set the q-option-group selected value for you behind the scene.
A simple demo with dynamic checkbox:
var demo = new Vue({
el: '#demo',
data: {
checked: [],
categories: [{ Id: 1 }, { Id: 2 }]
},
mounted(){ this.checked = [2] }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="demo">
<ul>
<li v-for="c in categories">
<input type="checkbox" :value="c.Id" :id="c.Id" v-model="checked" />
{{c.Id}}
</li>
</ul>
</div>

Bootbox incorrectly submits a form when a single input field is present

I have a strange problem that's really starting to bug me. Apologies in advance for a wall of code and somewhat confusing question.
I need to display a modal form for the user, and have them fill in some details.
The user can click Save to save their changes.
The user can click Cancel to cancel their changes.
I use the save handler to serialize the form and send its data to a JSON service.
If I have a form with multiple input fields, it all works great, and nothing unexpected happens.
If I have a form with a single input field, however, I get an unexpected side-effect. Hitting Enter/Return in that input field causes the modal form to be submitted, and instead of my JSON handler getting called the page is reload with the form's arguments as parameters — exactly as if the form is being submitted. In fact, adding an action= parameter to the form element has proven that, as you get navigated to the page you specify.
Here's the form I'm using:
<form id="surveyQuestionForm" class="form-horizontal" style="display:none;">
<div class="row">
<input name="surveyQuestionId" id="surveyQuestionId" type="hidden">
<input name="surveyId" type="hidden" value="${survey.surveyId}">
<div class="control-group">
<label class="control-label" for="questionType"><b><spring:message code="survey.question.type"/></b></label>
<div class="controls">
<select class="input-large" name="questionType" id="questionType">
<option value="">(Select one)</option>
<c:forEach items="${surveyQuestionTypes}" var="surveyQuestionType">
<option value="${surveyQuestionType.code}">${surveyQuestionType.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="questionText"><b><spring:message code="survey.question.text"/></b></label>
<div class="controls">
<input type="text" class="input-xlarge" name="questionText" id="questionText" maxLength="64"/>
</div>
</div>
</div>
</form>
and here's the code I use to display the form modally:
function addQuestion() {
// find the form, and initialise its validation.
var form = $('#surveyQuestionForm');
var validator = form.validate(
{
rules: {
questionType: {
required: true
},
questionText: {
required: true
}
},
messages: {
questionType: {
required: '<spring:message javaScriptEscape="true" code="survey.question.type.required"/>'
},
questionText: {
required: '<spring:message javaScriptEscape="true" code="survey.question.text.required"/>'
}
},
onkeyup: false
});
// reset form validation, and hide any error message
validator.resetForm();
$("#errorMessage").hide();
// show the dialog
bootbox.dialog({
title: '<i class="icon-plus green"/> <spring:message javaScriptEscape="true" code="survey.add.question"/>',
message: form,
closeButton: false,
buttons: {
cancel: {
label: '<i class="icon-remove bigger-130"></i> <spring:message javaScriptEscape="true" code="button.cancel"/>',
className: "btn btn-danger"
},
save: {
label: '<i class="icon-ok bigger-130"></i> <spring:message javaScriptEscape="true" code="button.save"/>',
className: 'btn btn-success',
callback: function () {
var result = false;
if (!form.valid())
return false;
$.ajax({
type: "POST",
url: '/addSurveyQuestion.json',
async: false,
data: form.serialize(),
success: function (outcome) {
if (outcome.success) {
$('#question-list').dataTable().fnReloadAjax();
result = true;
}
else {
$("#errorMessage").html(htmlEncode(outcome.message)).show();
}
}
}
).fail(function () {
$.gritter.add({
title: '<spring:message javaScriptEscape="true" code="general.error"/>',
text: '<spring:message javaScriptEscape="true" code="server.error"/>',
class_name: 'gritter-error'
}
);
}
);
return result;
}
}
},
show: false,
animate: false,
onEscape: false
}
).on('shown.bs.modal', function () {
var form = $('#surveyQuestionForm');
form.find('#surveyQuestionId').val(null);
form.find('#questionType').val('');
form.find('#questionText').val('');
form.show().find('#questionType').focus();
form.show();
}
).on('hide.bs.modal', function (e) {
if (e.target === this)
$('#surveyQuestionForm').hide().appendTo('body');
}
).modal('show').addClass("bootboxDialog40");
}
If I use this code as-is, with Bootbox 4.4, hitting Enter/Return while the user is in the questionText field submits the form, and my page redisplays but with the form fields as parameters, eg:
page.html?surveyQuestionId=&surveyId=3&questionType=Y&questionText=blah
If I have a second input field, hitting Enter/Return in the fields does nothing, and the user has to click Save or Cancel.
Submit-on-enter for a single input field is a browser behavior that you will need to override. You can do this a few ways.
<form onSubmit="return false;">
I don't think you are using the native submit function at all, so adding this bit of inline scripting prevents the form submission. But putting scripts in your markup isn't great. A little jQuery can do the same thing for you:
$('form').on('submit', function(){ return false; });
I believe this is not related to bootbox plugin. The actual reason is here:
https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
Coming to the solution, you can add another hidden field in your form which will prevent the submission of the form on enter.

jQuery validation condition based on elements selection

I have following input elements on my form and and validation form with jQuery validation plugin.
HTML:
<form name='frmUsers' id='frmUsers' method='post' action='#'>
<div>
<input type='text' name='name' id='name' placeholder='Name' />
</div>
<br />
<div>
<input type='text' name='fixed_budget' id='fixed_budget' placeholder='Fixed budget' />
</div>
<br />
<div>
<select name='budget' id='budget'>
<option value=''>Select your budget</option>
<option value='1000'>1000</option>
<option value='2000'>2000</option>
<option value='3000'>3000</option>
<option value='4000'>4000</option>
</select>
</div>
<br/>
<div>
<input id='save' type='submit' value='Save' />
</div>
</form>
jQuery validation:
$(document).ready(function () {
$("#frmUsers").validate({
onkeyup: false,
onfocusout: false,
ignore: [],
rules: {
"name": {
required: true
},
"fixed_budget": {
required: true
},
"budget": {
required: true
}
},
messages: {
"name": {
required: 'required'
},
"first_name": {
required: 'required'
},
"last_name": {
required: 'required'
}
},
errorPlacement: function (error, element) {
},
submitHandler: function () {
return false;
}
});
});
Now all elements are required fields but I have specific condition on Fixed budget (text box) and budget (select box).
For example:
When user click on submit, fixed budget and budget elements display with errors but (1) when user select any option on budget, set fixed budget field to not required. (2) when user input something on fixed budget set budget field to not required.
Here is my working JSFiddle: http://jsfiddle.net/mananpatel/85KR4/384/
Any Idea?
Thanks.
(1) when user select any option on budget, set fixed budget field to not required. (2) when user input something on fixed budget set budget field to not required.
In other words, you only require one of those two fields filled out.
Include the additional-methods.js file and use the require_from_group method.
rules: {
name: {
required: true
},
fixed_budget: {
require_from_group: [1, ".requiredGroup"]
},
budget: {
require_from_group: [1, ".requiredGroup"]
}
},
DEMO: http://jsfiddle.net/7om97gk8/
Note:
Use return false within the errorPlacement function if you want to suppress messages. Don't leave the function empty, as that's sloppy coding.
errorPlacement: function (error, element) {
return false;
},
Also, use the latest version of the plugin file as this will ensure the require_from_group method operates bug-free.
I don't understand why you are using the messages option when you've totally disabled these messages from displaying. You can safely remove messages in this case.

Jquery validation plugin errorplacement for single element

i am using Jquery validation plugin for validating the form.when validating the form for one element alignment is not proper.
If you see the image,for the city field icon + button alignment not proper when it validating the form. Because label error validation is displaying in between the input element and icon +. I need to display the error message below of the element.
My html code is like this for the city field
<tr>
<td align="right"><span class="mandetry">*</span> City:</td>
<td>
<div class="input-group" id="app_details">
<input type="text" class="form-control client_city" name="client_city" id="city_name" value="<?php echo set_value('client_city')?>">
<span class="input-group-btn">
<a class="btn btn-default" id='addnewcity' href="<?php echo base_url('addnewcity')?>"><i class="fa fa-plus-square"></i></a>
</span>
<div id="messageBox"></div> <!-- Here i would like to display message-->
</div> </tr>
js code is like this
$(document).ready(function(){
$('#add_client').validate({
errorClass: 'validation_errors',
debug: false,
rules: {
client_name:{required:true},
client_address:{required:true},
client_city:{required:true},
errorPlacement: function(error, element) {
if (element.attr("name") == "client_city" )
{
error.appendTo("#messageBox");
}
}
},
messages: {
client_name:{required:"The Client name is a required / mandatory field"},
client_address:{required:"The Client address is a required / mandatory field"},
client_city:{required:"The City is a required / mandatory field"},
}
});
});
Error message not appended to messageBox div.Is there any wrong with errorPlacement in js. For only city element i need to display the error message properly. For other form fields it shouldn't change.i am unable to solve this issue. Please suggest me. Thanks.
You are missing the else part, if it is not the client_city element then you need to insert the error after
$(document).ready(function () {
$('#add_client').validate({
errorClass: 'validation_errors',
debug: false,
rules: {
client_name: {
required: true
},
client_address: {
required: true
},
client_city: {
required: true
}
},
errorPlacement: function (error, element) {
console.log('dd', element.attr("name"))
if (element.attr("name") == "client_city") {
error.appendTo("#messageBox");
} else {
error.insertAfter(element)
}
},
messages: {
client_name: {
required: "The Client name is a required / mandatory field"
},
client_address: {
required: "The Client address is a required / mandatory field"
},
client_city: {
required: "The City is a required / mandatory field"
},
}
});
});
Demo: Fiddle

Conditional validation with jquery

Ok this is driving me crazy. I have a user account page. Where you have the option to change your password. I want a conditional jquery validation that if the user types in a new password in the new password box the box that confirms the password as well as the box that asks for the old password is turned into a required element. here is my ragtag code so far:
$("#aspnetForm").validate({
rules: {
<%=CurrentPass.UniqueID %>: {
required: <%=NewPass1.UniqueID %>:specified}
<%=NewPass2.UniqueID %>: {
required: <%=NewPass1.UniqueID %>:specified}
}, messages:{}
});
Just to clear something up. I am using :specified because if the filed is filled. Maybe some other condition?
I think you want to use equalTo for the confirmation password, with the current password required if the new password has data in it.
$('form').validate({
rules: {
<%= CurrentPass.UniqueID %>: {
required: '#<%= NewPass1.ClientID %>:filled'
},
<%= NewPass2.UniqueID %>: {
equalTo: '#<%= NewPass1.ClientID %>'
}
}
});
Those selectors need to be strings using :filled (unless :specified is a custom selector you made) and found by ID instead of name, like this:
$("#aspnetForm").validate({
rules: {
<%=CurrentPass.UniqueID %>:{
required: "#<%=NewPass1.ClientID %>:filled"}
<%=NewPass2.UniqueID %>:{
required: "#<%=NewPass1.ClientID %>:filled"}
}, messages:{}
});
});

Categories