Javascript Checkbox Required Funcion Only for 1 Form - javascript

I'm trying to use the following JS that I found around here and since I have multiple forms on a page I would like to customize the function to only work with specific form ID.
In my case <form id="car" ...
// required checkboxes
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});

You have to modify your query as follows in order to select only the checkboxes from your form:
var requiredCheckboxes = $("#car").find(':checkbox[required]');

Related

Hide field based on checkbox using javascript in odoo 12

I have two fields, field1 is a checkbox and field2 is a normal text field. I want to hide a field2 if a field1 is not checked and if
field1 is checked then show field2. For that, I am creating the following code:
odoo.define('survey_inherit.FormView', function (require) {
"use strict";
var FormView = require('web.FormView');
var core = require('web.core');
var QWeb = core.qweb;
var FormView = FormView.extend({
_checkField: function(){
var $checkbox = $('.custom-control-input').val();
if ($checkbox.is(':checked')) {
$('.o_form_label').show();
$('.mandatory_msg_class').show();
}else{
$('.mandatory_msg_class').hide();
}//close else
},
});//close FormController
return FormView;
});
But field2 is not hidden if field1 is not checked and also field2 is not shown if field1 is checked.
Update
My requirement is that I have one form which contains a one2many field with widget many2many_tags and other fields. After clicking on tags of many2many_tags, I want to display the complete records in other fields. I am able to get complete records after a click on tags and also these records are able to put in other fields. After using attrs and opening form view for creating records field2 will never display. But open form view in edit mode after creating a record and click on many2many_tags
field2 is not displayed because of attrs.
Removing attrs and opening form view for creating records field will display(but don't want to display because field1 is not checked) and open form view in edit mode after creating a record, click on many2many_tags work fine as expected.
Attrs condition: attrs="{'invisible':[('constr_mandatory','!=',True)]}"
constr_ mandatory: checkbox field
This is the reason I am not using attrs and trying to achieve with the help of javascript. I hope the provided information is understood. Also, I have updated the question added screenshots for better understanding.
Using attrs:
Using attrs click on many2many_tags
Without using attrs:
You can add a new widget and override the click method.
I did this with a BooleanToggle field.
var basic_fields = require('web.basic_fields');
var Toggle = basic_fields.BooleanToggle.extend({
_onClick: function (event) {
var self = this;
this._super(event);
var node = event.view.$('.custom-control-input');
if(this.value) {
node.show();
} else {
node.hide();
}
},
});
fieldRegistry.add('toggle', Toggle);
You need to add the widget attribute:
field name="field1" widget="toggle"/>
Edit
You need to hide the fields after the form loaded, I suggest to you to override the autofocus function of the FormRenderer.
var FormRenderer = require('web.FormRenderer');
FormRenderer.include({
autofocus: function () {
var self = this;
// In my test I used fields values available in "self.state.data"
if(self.state.model === 'sale.order' && field_value){
var nodes = window.$('.custom-control-input');
nodes.hide();
}
return this._super();
},
});
var $checkbox = $('.custom-control-input').val();
This line set $checkbox to the checkbox's value. May be you just want the checkbox element itself:
var $checkbox = $('.custom-control-input');
Try jQuery
$(function() {
$("#selpoNO").click(function() {
if ($(this).is(":checked")) {
$(".if_pucEntry").show();
} else {
$(".if_pucEntry").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- checkbox -->
<label class="led-label"><input type="checkbox" class="led-btn" name="selpoNO" id="selpoNO" style="width: auto !important;"><strong>Checkbox</strong></label>
<!-- text box -->
<input type="text" class="form-control if_pucEntry" id="" name="" style="display: none;">

Create button which takes to a particular URL according to data in Form Field

I've two input form fields and i want when the user clicks a submit button he should be taken to a URL based on the input in these two fields. For example if the input in the two input fields is A and B respectively the condition should be set such that the User is taken to www.mydomain.com/C in Javascript. I DON'T want the values to be appended to the URL like www.mydomain.com/a/b which I already know how to.
I have seen lot of questions on SO and Google on URL Generation but none was the case as mine. I would really appreciate help from fellow SO users. Thanks in advance.
Do you mean something like this? This would take you to the address when both inputs have the value 'something' and the button is clicked.
<input type="text" id="a">
<input type="text" id="b">
<button onclick="go()">Go</button>
<script>
function go() {
if (document.getElementById('a').value == 'something' && document.getElementById('b').value == 'something') {
window.location = 'http://www.example.com/C';
}
}
</script>
If you are using jquery:
$( "form" ).submit(function() {
// TODO read your variables
// TODO apply conditions and redirect accordingly
if ( ... ) {
window.location = 'http://www.example.com/C'
} else {
window.location = 'http://www.example.com/D'
}
return false; // prevent default submit
});

Form validation with jQuery Validate plugin

after a long research on internet i'm about to give up, let's say you are my last hope. My problem: I'm implementing a timesheet form for my company. This form is dynamic because in a day you can do several activities. The fields (included in a PHP page) are:
Day (text field)
Hours (drop down)
Notes (a text field where the employee can write notes for the day)
All the fields listed are in a row enclosed in a fieldset. On the top of field set i've put a button, clicking it I will add another row with the data listed before. Now, before submitting to backend, I want, of course, put some validation rules which are the following:
Field DAY must be required (it's my key in DB and i've added a DatePicker plugin)
The sum of hours in an entire day can't exceed the 8 hours
I've tried to use Jquery Validate but seems I have two problems:
It can't handle in somehow the arrays of data going to the script php that will write down on DB (for example the days submitted will arrive to backend in an array, I've decided this way because the number of days that can be recorded is not known before submission)
It adds the controls only on first row
I've tried (as I've read in other posts) to add rules after the creation of new row, but, in that case, it works on other fields only if i put the cursor inside, I leave the field blank and then I click outside that field.
I attach my code, any help would be appreciated!!
greetings from Italy.
<script type="text/javascript">
$(document).ready(function() {
var i = 0;
//fadeout selected item and remove
$('.remove').live('click', function() {
$(this).parent().fadeOut(300, function(){
$(this).empty();
return false;
});
});
$('a#add').click(function() {
i++;
var options = '<p>Day <input type="text" id = "Day'+i+'" class = "Day" name="day[]"> </select> hours<select id = "hours'+i+'" class = "hours" name="hours[]"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option></select> Notes <input type="text" id="Note'+i+'" class = "Note" name="note[]"><img src="images\\remove.png" height="20" width="20"></img></p>';
$(options).fadeIn("slow").appendTo('#extender');
});
$('.Day').live('click', function() {
$(this).datepicker('destroy').datepicker({
changeMonth: false,
changeYear: false,
stepMonths: false,
dateFormat: "dd-mm-yy",
showOn:'focus'}).focus();
});
});
</script>
this is where the dynamic fields are appended
<form name="rec_abs" method="post" action = "rec_on_db.php">
<fieldset>
<legend>Timesheet</legend>
<div id="extender"></div>
<p><img src="images\add.png" alt="" border=3 height=20 width=20></img> </p>
</fieldset>
</form>
<input type="submit" value="Send your timesheet"></input><br>
Regarding the fact that your elements are only validated when you change them, you can try using the plugin's onsubmit option:
$("form[name='rec_abs']").validate({
onsubmit:true
});
When it comes to validating multiple fields, I'd suggest adding a class rule to your validation using the addClassRule method.
Define your rule the following way:
$.validator.addClassRules("my-day", {
required: true
});
Then add the my-day class to your day elements.
Regarding the sum of the hours, look into the addMethod method. It enables you to define custom validation rules. Here's an example that checks if a phone number is in the +XXXXXX format (X is a number, + is optional):
$.validator.addMethod("phone", function(value, element) {
// no phone number is a good phone number (the field is optional)
if (value.length == 0) { return true; }
// use a regexp to test the if the value is in the '+XXXXXX..' form
return /^\+?(\d){5}\d+/i.test(value);
}, 'Invalid phone number');
I've managed to get my validation to work on ajax loaded content before, while retaining my script in a separate file using class rules and custom methods.
Thanks for reply Sir Celsius. Now with the first modification you suggested I can validate my form at submit. There is more than this by the way. I modified the code generating the dynamic form as follows:
$('a#add').click(function() {
i++;
var options = ' .... html of the row as before ...';
$(options).fadeIn("slow").appendTo('#extender');
$('#Day'+i).rules('add', {
required: true,
messages: {
required: ""
}
});
$('#Hours'+i).rules('add', {
required: true,
messages: {
required: ""
}
});
});
With these lines I add rules at newly created parts of document. I've put a counter just to make every cell have its own ID, class name remains the same. For my purpose I have to put data in arrays, every type of data has its own vector. Here is the problem. If all the fields have different IDs (OK for HTML), same CLASS (OK for HTML), BUT SAME NAME (ok for HTML but not for Jquery validation), the validation is operated only on the first row! To accomplish the aim I've made a modification to query.validate.js putting this code:
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
} else {
this.check( elements[i] );
}
}
return this.valid();
}
replacing the "standard" form
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
this.check( elements[ i ] );
}
return this.valid();
}
as suggested at link Jquery Validation validate form-array. Now the validation works perfectly. I will work at second part of validation (sum of hours) and I'll let you know! Thank you so much for the moment!

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

Unable to remove form elements while using element.parentNode.removeChild(element)

I have a form that will submit to a Google search appliance, forming a query string "q".
In the form I have radio buttons and a hidden element; the radio buttons contain options for sites to select; the hidden element contains multiple sites that will allow the user to select multiple site searches.
<input type="radio" id="site_search" name="as_sitesearch" value="www.mycompany.com" checked>Current site<br />
<input type="radio" id="site_search" name="as_sitesearch" value="archive.mycompany.com">Archive site<br />
<input type="radio" id="site_search" name="as_sitesearch" value="">Both sites<br />
<input type="hidden" id="as_oqOption" name="as_oq" value="www.mycompany.com archive.mycompany.com">
This is the Javascript I wrote that will remove the radio element or the hidden element exclusively (one of them can exist in the form submittal):
// IF THE USER CHECKED "BOTH SITES", YOU WILL HAVE TO WIPE OUT THE VALUE OF as_sitesearch TO ALLOW FOR PASSING OF as_oq FOR GOOGLE ENGINE
if (form.elements['as_sitesearch'][0].value.length == 0) {
var goodbyeElement = document.getElementById('site_search');
goodbyeElement.parentNode.removeChild(goodbyeElement);
} else {
var goodbyeElement = document.getElementById('as_oqOption');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}
However, when the form is submitted, "q" winds up obtaining both radio and hidden elements no matter what radio option I click.
Not sure why this is happening as I followed the guides in the DOM tutorial sites I have read on how to remove a form element prior to submittal. Any ideas?
Thanks
Following code may help you:
(form.as_sitesearch[2].checked){
for(var k=0; k<form.as_sitesearch.length;k++){
form.as_sitesearch[k].parentNode.removeChild(form.as_sitesearch[k])
}
}
else{
var goodbyeElement = document.getElementById('as_oqOption');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}
You should call it on form submit. here form is document.form[index];
Got it! Apparently form.elements will always fail because of the grouping, so don't use it..
// IF THE USER CHECKED "BOTH SITES", YOU WILL HAVE TO WIPE OUT THE VALUE OF as_sitesearch TO ALLOW FOR PASSING OF as_oq FOR GOOGLE ENGINE
if (document.getElementById('site_search3').checked) {
for (var i = 1; i <= 3; i++) {
eval('var goodbyeElement = document.getElementById("site_search' + i + '");');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}
} else {
var goodbyeElement = document.getElementById('as_oqOption');
goodbyeElement.parentNode.removeChild(goodbyeElement);
}

Categories

Resources