Knockoutjs checked binding function call issue - javascript

I am trying to call a function when the check box is checked and set the field values accordingly. The checkbox and the address fields are like below
<div class="form-check">
<input class="form-check-input position-static" type="checkbox" id="SameAsShippingAddress" value="SameAsShippingAddress" data-bind="checked: sameAsShippingAddress" />
<label>Check this box if Shipping Address and Billing Address are the same.</label>
</div>
<div class="row">
<div class="col-md-6">
<h4>Shipping Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor" name="EmailCompetitor" class="form-control" data-bind="value: emailCompetitor" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor" name="FirstNameCompetitor" class="form-control" data-bind="value: firstNameCompetitor" required />
</div>
</div>
<div class="col-md-6">
<h4>Billing Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor_Billing" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor_Billing" name="EmailCompetitor_Billing" class="form-control" data-bind="value: emailCompetitor_Billing" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor_Billing" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor_Billing" name="FirstNameCompetitor_Billing" class="form-control" data-bind="value: firstNameCompetitor_Billing" required />
</div>
</div>
I want the check box boolean value captured seperately as well as when check box is checked it needs to call the function. So in js I have like
var orderRequestFormViewModel = function () {
var self = this;
self.currentPage = ko.observable(1);
self.referringPage = ko.observable();
...............
self.sameAsShippingAddress = ko.observable().extend({ required: false });
..........
self.sameAsShippingAddress = function () {
if (this.checked) {
$("#EmailCompetitor_Billing").val($("#EmailCompetitor").val());
$("#FirstNameCompetitor_Billing").val($("#FirstNameCompetitor").val());
} else {
$("#EmailCompetitor_Billing").val("");
$("#FirstNameCompetitor_Billing").val("");
}
}
But when the checkbox is checked/unchecked this function is not being called at all
I tried put the breakpoint but the function is not being it. New to this JS world, any help is greatly appreciated

Hey I made you a little snippet to show you that it works perfectly fine when using an observable and checked binding, when checkbox is checked, it is "true" if not it´s "false"
To make custom stuff like setting .val() of other input just use a computed function, it will be called whenever isChecked changes
var model = function () {
var self = this;
self.isChecked = ko.observable(false);
self.doStuffWhenChecked = ko.computed(function(){
if(self.isChecked()){
$('#textinput').val("whatever");
}else{
$('#textinput').val("");
}
},this);
}
var vm = new model();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>Check this: </label>
<input type="checkbox" data-bind="checked: isChecked">
<span data-bind="visible: isChecked()"> Only show when checked </span>
<input type="text" id="textinput" >

Related

After selecting the date of birth in the drop-down box, my age cannot be displayed in real time. Why?

Here’s my front-end page:
Here is part of my code:
<div class="col-xs-4">
<div class="form-group">
<label class="col-sm-6 control-label" style="text-align: left"><#spring.message "bornDate"/>:</label>
<label class="col-sm-6 control-label" name="input-text" id="bornDate" style ="text-align: left"><input id="bornDateTmp" style="width:90px;" data-bind="value: model.bornDate"/></label>
<script>
$("#bornDateTmp").kendoDatePicker({
format: "{0:yyyy/MM/dd}"
}).data("kendoDatePicker");
</script>
</div>
</div>
...
...
<div class="col-xs-4">
<div class="form-group">
<label class="col-sm-6 control-label" style="text-align: left">
<#spring.message "age"/>:
</label>
<label class="col-sm-6 control-label" name="" id="age" style ="text-align: left">
<span id="ageTmp" data-bind="text:model.age">
<script>//here,here,here!!!
$("#ageTmp").text(basicInformation.model.age.getFullYear-new Date().getFullYear());
</script>
</span>
</label>
</div>
</div>
In addition, I would like to make a special note that the internal framework of the company is used for data binding:
<script type="text/javascript">
var basicInformation = kendo.observable({
model: {
},
});
$.ajaxSetup({async: false});
Hap.loadViewModel({
url: '${base.contextPath}/xxentry/people/info/collection/basicInfo',
model: basicInformation.model
});
$.ajaxSetup({async: true});
</script>
The problem is, when I choose my date of birth, the age doesn’t show up in real time, but on the chrome console, it works!I've been thinking about it all day.
Try to bind the change event on the date picker. On change calculate your age and bind it to the observable variable, bind that variable to your age element.
Something like this:
<input id="bornDateTmp" style="width:90px;" data-bind="value: model.bornDate, events: {change: onDateChange}"/>
var basicInformation = kendo.observable({
model: {
},
onDateChange: function(e) {
var selectedDate = this.model.bornDate;
var age = //calculate age;
this.model.set('age', age);
}
});
<span id="ageTmp" data-bind="text:model.age">
Working example: On change show value

React.js: The value from variable was changed after checkbox but not written in <imput value={...}.../>

One of the form fields: address Actual and address of registration. With an active checkbox, the address Actual should be equal to the address of registration. But in fact, the address Actual is not recorded in a variable.
When checkbox is active, call checkBoxAddress:
checkBoxAddress = () => {
this.setState({checked: !this.state.checked});
}
Then check the checkbox before return(...), and change the value of the variable:
if (this.state.checked) {
addressActual = passportAddress;
console.log(addressActual) // There are true value, worked. But not in form value
}
Form:
...
<div className="form-group col-md-12">
<input name="passportAddress" type="text" className="form-control"
placeholder="Адрес прописки"
value={passportAddress} onChange={this.changeHandler}/>
</div>
</div>
<div className="form-check">
<div className="form-group">
<input className="form-check-input" type="checkbox" id="gridCheck"
onChange={this.checkBoxAddress}
defaultChecked={this.state.checked}/>
<label className="form-check-label" htmlFor="gridCheck">
Адрес прописки совпадает с почтовым
</label>
</div>
</div>
<div className="form-row">
<div className="form-group col-md-12">
<input name="addressActual" type="text" className="form-control"
placeholder="Адрес почтовый"
value={addressActual} onChange={this.changeHandler}/>
</div>
...
In the input field, the address is substituted, but not stored in the variable:
pasportAddress="12345", addressActual=""
checkBoxAddress = () => {
console.log(this.state.checked)
this.setState({checked: !this.state.checked})
if (!this.state.checked) {
this.setState({addressActual: this.state.passportAddress})
}
};
Now, it's worked.

Jquery Validation plug-in dependency from Radio buttons not working

I need some inputs to be required only if certain options are checked in another input (radio). In short, if Type 1 documents is chosen, I need type 1 field number to be obligatory. It's easier to visualize through this jsfiddle below:
https://jsfiddle.net/kbhatd51/2/
Could you please help me? Thanks in advance
<form id="registerform" method="post">
<div class="form-group">
<label >Type of Document</label><br>
<input type="radio" class="radioForm" id="fis" name="tipop" value="0" > <label for="fis"> Type 1</label><br>
<input type="radio" class="radioForm" id="jur" name="tipop" value="1" > <label for="jur"> Type 2</label><br>
</div>
<label for="tipop"> Number</label>
<div class="form-group">
<fieldset id="cpf1">
<label for=cpf1>Type 1 No.:</label>
<input type="number" class="form-control" placeholder="000.000.000-00" name="cpf" id="cpf" >
</fieldset>
<fieldset id="cnpj1">
<label for=cnpj1> Type 2 No.:
<input type="number" class="form-control" placeholder=" 00.000.000/0001-00" name="cnpj" id="cnpj"></label>
</fieldset>
</div>
<input name="submit" type="submit" value="Submit!">
</form>
JS validate:
$("#registerform").validate({
rules: {
cpf: {
required: "#fis:checked"
},
cnpj: {
required: "#jur:checked"
}
}
});
The required method needs to return true for the field to be required.
So you can simply pass a function to required which will check if the radio element is checked
required method
required( dependency-callback )
Type: Function()
The function is executed with the element as it's only argument: If it returns true, the element is required.
$("#registerform").validate({
debug: true,
rules: {
cpf: {
required: function(elem) {
return $('#fis').is(":checked")
}
},
cnpj: {
required: function(elem) {
return $('#jur').is(":checked")
}
}
}
});
Check out the -- JSFiddle Example -- here.

Auto populate dropdown fields doesn't work

I have 2 drop down fields which both auto populated.
Example :
car_model -> dropdown_field1
car_model_variants -> dropdown_field2
When I select a model in car_model field, car_model_variants must update its values.
In my case, I have index.php where you can click a button that will show the modal box and you'll find the auto populated drop down fields.
First attempt, when selecting a car_model it works the car_model_variants field is updating its values. But it doesn't work if I submit a form when car_model_variants is empty, If I try to select a car_model again? the dropdown 2 field is not updating. Below is my code.
(function ($) {
$('.edit').formPopup({
'modalParams': {
'parent_container': $('div.autodeal')
},
'callback': function (settings)
{
$('.modal')
.addClass('large')
.css({'z-index': 101});
$('#used_car_car_model').change(function () {
var select = $(this);
$.ajax({
'url': '{{ path("autodeal_backend_filter_select") }}',
'data': {'carModelId': select.val(), 'carGuideOnly': 0, 'isVerified': 1, 'showCompleteName': 1},
success: function (html)
{
$('#used_car_car_model_variant').html(html);
}
});
});
},
'formSubmitParams': {
'retainFormUrl': false,
'submit_callback': function ()
{
window.location.reload();
},
'error_callback': function (form, settings)
{
$('.close, .exit', $(settings.container))
.click(function () {
window.location.reload();
});
}
}
});
})(jQuery);
Here's the full code.
<form novalidate="" action="/app_dev.php/used-car-listings/164/edit" method="POST">
<div class="marginbottom row gutters">
<div class="col span_12">
<div>
<div>
<label for="used_car_plate_number" class="required">Plate number</label>
<input type="text" id="used_car_plate_number" name="used_car[plate_number]" required="required" value="GS0909">
</div>
<div>
<label for="used_car_year" class="required">Year</label>
<input type="text" id="used_car_year" name="used_car[year]" required="required" value="2015">
</div>
<div>
<label for="used_car_car_model" class="required">Car Model</label>
<select id="used_car_car_model" name="used_car[car_model]" required="required">
<option value="">Select A Model</option><option value="102">Mercedes-Benz A-Class</option><option value="401" selected="selected">Mercedes-Benz AMG</option><option value="103">Mercedes-Benz B-Class</option><option value="105">Mercedes-Benz C-Class Coupe</option><option value="104">Mercedes-Benz C-Class Sedan</option><option value="115">Mercedes-Benz CLA-Class</option><option value="576">Mercedes-Benz CLC-Class</option><option value="577">Mercedes-Benz CLK-Class</option><option value="106">Mercedes-Benz CLS-Class</option><option value="107">Mercedes-Benz E-Class</option><option value="578">Mercedes-Benz G-Class</option><option value="108">Mercedes-Benz GL-Class</option><option value="109">Mercedes-Benz GLK-Class</option><option value="110">Mercedes-Benz M-Class</option><option value="111">Mercedes-Benz S-Class</option><option value="112">Mercedes-Benz SL-Class</option><option value="113">Mercedes-Benz SLK-Class</option><option value="114">Mercedes-Benz SLS-Class</option><option value="579">Mercedes-Benz Viano</option></select>
</div>
<div>
<label for="used_car_car_model_variant" class="required">Car Model Variant</label>
<select id="used_car_car_model_variant" name="used_car[car_model_variant]" required="required"><option value="">Select Mercedes-Benz A-Class Variant</option><option value="343">2014 Mercedes-Benz A-Class A 250 Sport 4MATIC</option><option value="344">2014 Mercedes-Benz A-Class A 45 AMG</option></select>
</div>
<div>
<label for="used_car_mileage" class="required">Mileage</label>
<input type="text" id="used_car_mileage" name="used_car[mileage]" required="required" value="1700">
</div>
<div>
<label for="used_car_price" class="required">Price</label>
<input type="text" id="used_car_price" name="used_car[price]" required="required" value="3288300">
</div>
<div>
<label for="used_car_used_car_color" class="required">Color</label>
<select id="used_car_used_car_color" name="used_car[used_car_color]" required="required">
<option value="">Select A Color</option><option value="1">Red</option><option value="2">Blue</option><option value="3">Black</option><option value="4">White</option><option value="5">Green</option><option value="6">Silver</option><option value="7" selected="selected">Grey</option><option value="8">Yellow</option><option value="9">Brown</option><option value="10">Beige</option><option value="11">Orange</option><option value="12">Purple</option><option value="13">Pink</option><option value="14">Turquoise</option><option value="15">Bronze</option></select>
</div>
<div>
<label for="used_car_description" class="required">Description</label>
<textarea id="used_car_description" name="used_car[description]" required="required" cols="4" rows="3">Body color, Tenorite Gray</textarea>
</div>
<div>
<label class="required">City</label>
<input type="hidden" id="used_car_city_id" name="used_car[city][id]" value="20"><input type="text" id="used_car_city_text" name="used_car[city][text]" required="required" autocomplete="off" value="San Juan, Metro Manila">
</div>
<div>
<label class="required">Is service record submitted</label>
<div id="used_car_is_service_record_submitted"><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_0" name="used_car[is_service_record_submitted]" required="required" value="1">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_1" name="used_car[is_service_record_submitted]" required="required" value="0" checked="checked">No</label></div>
</div>
<div>
<label class="required">Is LTO verified</label>
<div id="used_car_is_lto_verified"><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_0" name="used_car[is_lto_verified]" required="required" value="1" checked="checked">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_1" name="used_car[is_lto_verified]" required="required" value="0">No
</label></div>
</div>
<div>
</div>
</div>
<input type="hidden" id="used_car__token" name="used_car[_token]" value="4e4UOHBr5SmtV7Pb0WoWv4xSz90LoVarNG8hw0dy_RY"> <hr class="nomargin marginbottom30 margintop20">
<div class="row">
<button type="submit" class="button">Save</button>
</div>
</form>

onchange can't find function

I'm trying to make an input change value depending on another inputs value.
What I've come up with so far is this. But when running the onchange commmand I get an error that updateCity doesn't exist. Even thou it's there. Am I doing something wrong, is pretty new to coding with javascript.
<div class="form-inline">
<div class="form-group">
<label class="sr-only" for="zip">Indtast postnummer</label>
<input class="form-control" type="text" name="register_zip" id="zip" placeholder="Indtast postnummer" value="#city.zip" onchange="updateCity(this.value)" />
</div> <!-- class="form-group" -->
<div class="form-group">
<label class="sr-only" for="city">Indtast by</label>
<input class="form-control" type="text" name="register_city" id="city" placeholder="Indtast by" value="#city.name" />
</div> <!-- class="form-group" -->
</div>
<script>
function updateCity(city_zip) {
var city = findCity(city_zip);
if(city != null){
document.getElementById("register_city").value = city_name;
}
};
function findCity(zip){
var cities = [];
#{
foreach (var c in cities)
{
<text>
cities.push({zip: #c.zip, name: #c.name});
</text>
}
}
for(var i=0;i<cities.length;i++){
if(cities[i].zip == zip){
return cities[i]
}
}
};
</script>

Categories

Resources