How to push values into array using radio buttons in angularjs - javascript

I am trying to push values to an array whenever i check the radio button. How can I accomplish this?
<div class="form-group" show-errors>
<div class="col-sm-12" >
<div class="form-group col-xs-12 nopadding" >
<label class="control-label" for="mobile">Have you taken any admission tests? (eg. IELTS, GRE, etc)</label>
<div class="btn-group col-xs-12 nopadding" data-toggle="buttons">
<label class="col-xs-6 btn btn-white" ng-click="checkMultiSelect(vm.studentObj,admission)" ng-class="{'active':vm.studentObj.test_taken === 'Y'}">
<input type="radio" name="test_taken" ng-model="vm.studentObj.test_taken" value="Y"> Yes
</label>
<label class="col-xs-6 btn btn-white" ng-click="checkMultiSelect(vm.studentObj,'test_taken','N')" ng-class="{'active':vm.studentObj.test_taken === 'N'}">
<input type="radio" name="test_taken" ng-model="vm.studentObj.test_taken" value="N"> No
</label>
</div>
</div>
</div>
</div>
<div class="form-group" show-errors>
<div class="col-sm-12" >
<div class="form-group col-xs-12 nopadding" >
<label class="control-label" for="mobile">Educational Info (High School/ Secondary/ Primary/ Pre School)</label>
<div class="btn-group col-xs-12 nopadding" data-toggle="buttons">
<label class="col-xs-6 btn btn-white" ng-click="checkMultiSelect(vm.studentObj,Educational)" ng-class="{'active':vm.studentObj.test_taken === 'Y'}">
<input type="radio" name="test_taken" ng-model="vm.studentObj.test_taken" value="Y"> Yes
</label>
<label class="col-xs-6 btn btn-white" ng-click="checkMultiSelect(vm.studentObj,'test_taken','N')" ng-class="{'active':vm.studentObj.test_taken === 'N'}">
<input type="radio" name="test_taken" ng-model="vm.studentObj.test_taken" value="N"> No
</label>
</div>
</div>
</div>
</div>
My function
$rootScope.checkMultiSelect = function (data, key) {
if (!data) {
data = [];
}
var idx = data.indexOf(key);
if (idx > -1) {
data.splice(idx, 1);
} else {
data.push(key);
}
};

You don't need to manually push data to get an object representing the form. The data-binding in Angular does this for you.
<form ng-form="studentForm">
<div class="form-group" show-errors>
<div class="col-sm-12" >
<div class="form-group col-xs-12 nopadding" >
<label class="control-label" for="mobile">Have you taken any admission tests? (eg. IELTS, GRE, etc)</label>
<div class="btn-group col-xs-12 nopadding" data-toggle="buttons">
<label class="col-xs-6 btn btn-white" ng-class="{'active':studentObj.test_taken === 'Y'}">
<input type="radio" name="test_taken" ng-model="studentObj.test_taken" value="Y"> Yes
</label>
<label class="col-xs-6 btn btn-white" ng-class="{'active':studentObj.test_taken === 'N'}">
<input type="radio" name="test_taken" ng-model="studentObj.test_taken" value="N"> No
</label>
</div>
</div>
</div>
</div>
<div class="form-group" show-errors>
<div class="col-sm-12" >
<div class="form-group col-xs-12 nopadding" >
<label class="control-label" for="mobile">Educational Info (High School/ Secondary/ Primary/ Pre School)</label>
<div class="btn-group col-xs-12 nopadding" data-toggle="buttons">
<label class="col-xs-6 btn btn-white" ng-class="{'active':studentObj.edu_info === 'Y'}">
<input type="radio" name="test_taken" ng-model="studentObj.edu_info" value="Y"> Yes
</label>
<label class="col-xs-6 btn btn-white" ng-class="{'active':studentObj.edu_info === 'N'}">
<input type="radio" name="test_taken" ng-model="studentObj.edu_info" value="N"> No
</label>
</div>
</div>
</div>
</div>
</form>
Say someone fills out the form with the first radio as yes and the second as no. The output of studentObj will be
{
test_taken: 'Y',
edu_info: 'N'
}
This is the beauty of Angular. You don't need to manually push values, the data-binding does all of this for you and you don't need to clutter up your controller with unnecessary code.

Related

Price calculation with javascript for my data in the loop coming from the database

I want the prices of the data coming from my database to be displayed on the screen with Javascript. I wrote a code like this but it only works this way. I may have more than one data from the database. For example, more than one title may come instead of gb or screen. I'm trying to loop for this but I couldn't. Could you help?
const values = {
gb: null,
display: null,
}
function PriceCalculator(label, newPrice) {
values[label] = newPrice;
if(values.gb != null && values.display != null){
var total = values.gb + values.display;
var result = Number(total).toLocaleString("pt-BR",{minimumFractionDigits: 2, maximumFractionDigits: 2});
document.getElementById("money").innerHTML=result;
}
}
<div id="form_step_1">
<div class="container">
<div class="row">
<div class="talepler mb-3">
<h4>GB</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio"
id="features-1"
name="1"
value="features-value-1"
data-money="-300"
data-product-money="2500"
onclick="PriceCalculator('gb', -300)"
>
<label class="btn btn-pill" style="display: inline-block;" for="features-1">16GB</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio"
id="features-2"
name="1"
value="features-value-2"
data-money="-200"
data-product-money="2500"
onclick="PriceCalculator('gb', -200)"
>
<label class="btn btn-pill" style="display: inline-block;" for="features-2">32GB</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio"
id="features-3"
name="1"
value="features-value-3"
data-money="-50"
data-product-money="2500"
onclick="PriceCalculator('gb', -50)"
>
<label class="btn btn-pill" style="display: inline-block;" for="features-3">64GB</label>
</div>
</div>
<h4>DISPLAY</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio"
id="features-1"
name="2"
value="features-value-1"
data-money="0"
data-product-money="2500"
onclick="PriceCalculator('display', 2500)"
>
<label class="btn btn-pill" style="display: inline-block;" for="features-1">Durable</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio"
id="features-2"
name="2"
value="features-value-2"
data-money="-1500"
data-product-money="2500"
onclick="PriceCalculator('display', 1500)"
>
<label class="btn btn-pill" style="display: inline-block;" for="features-2">Broken</label>
</div>
</div>
</div>
</div>
<div style="position:absolute; right: 0px;">
<div style="display: inline-block; margin-right: 20px"><strong>Pre-bid price:</strong> <div style="display: inline-block" id="money">Not calculated</div></div>
</div>
</div>
</div>
So like last time, delegate - I am using jQuery because your previous code used it. I'll add the vanilla one too
window.addEventListener("DOMContentLoaded", () => {
const total = document.getElementById("money");
document.getElementById("form_step_1").addEventListener("input", e => {
let sum = +e.target.closest(".container").dataset.productPrice;
document.querySelectorAll(".row h4").forEach(h4 => {
let title = h4.textContent,
container = h4.closest("div"), // parent
chosen = container.querySelectorAll("[type=radio]:checked");
if (chosen.length !== 0) {
chosen.forEach(rad => {
console.log(title,rad.value,Number(rad.dataset.discount))
sum += Number(rad.dataset.discount)
})
}
total.textContent = sum.toFixed(2);
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="form_step_1">
<div class="container" data-product-price="2500">
<div class="row">
<div class="talepler mb-3">
<h4>GB</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-1" name="1" value="features-value-1" data-discount="-300">
<label class="btn btn-pill" style="display: inline-block;" for="features-1">16GB</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-2" name="1" value="features-value-2" data-discount="-200">
<label class="btn btn-pill" style="display: inline-block;" for="features-2">32GB</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-3" name="1" value="features-value-3" data-discount="-50">
<label class="btn btn-pill" style="display: inline-block;" for="features-3">64GB</label>
</div>
</div>
</div>
<div class="talepler mb-3">
<h4>DISPLAY</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-1" name="2" value="features-value-1" data-discount="0">
<label class="btn btn-pill" style="display: inline-block;" for="features-1">Durable</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-2" name="2" value="features-value-2" data-discount="-1500">
<label class="btn btn-pill" style="display: inline-block;" for="features-2">Broken</label>
</div>
</div>
</div>
</div>
<div style="position:absolute; right: 0px;">
<div style="display: inline-block; margin-right: 20px"><strong>Pre-bid price:</strong>
<div style="display: inline-block" id="money">Not calculated</div>
</div>
</div>
</div>
</div>
jQuery
$(function() {
$("#form_step_1").on("input", function(e) {
let sum = +$(e.target).closest("div.container").data("price");
console.log(sum)
$(".row h4").each(function() {
let title = $(this).text(),
$container = $(this).closest("div"), // parent
$chosen = $container.find("[type=radio]:checked");
if ($chosen.length !== 0) {
$chosen.each(function() {
console.log(title,$(this).val(),Number($(this).data("discount")));
sum += Number($(this).data("discount"));
})
}
$("#money").text(sum.toFixed(2))
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="form_step_1">
<div class="container" data-price="2500">
<div class="row">
<div class="talepler mb-3">
<h4>GB</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-1" name="1" value="features-value-1" data-discount="-300">
<label class="btn btn-pill" style="display: inline-block;" for="features-1">16GB</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-2" name="1" value="features-value-2" data-discount="-200">
<label class="btn btn-pill" style="display: inline-block;" for="features-2">32GB</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-3" name="1" value="features-value-3" data-discount="-50">
<label class="btn btn-pill" style="display: inline-block;" for="features-3">64GB</label>
</div>
</div>
</div>
<div class="talepler mb-3">
<h4>DISPLAY</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-1" name="2" value="features-value-1" data-discount="0">
<label class="btn btn-pill" style="display: inline-block;" for="features-1">Durable</label>
</div>
<div class="col-sm-3 col-md-4 col-lg-3">
<input class="inputs" type="radio" id="features-2" name="2" value="features-value-2" data-discount="-1500">
<label class="btn btn-pill" style="display: inline-block;" for="features-2">Broken</label>
</div>
</div>
</div>
</div>
<div style="position:absolute; right: 0px;">
<div style="display: inline-block; margin-right: 20px"><strong>Pre-bid price:</strong>
<div style="display: inline-block" id="money">Not calculated</div>
</div>
</div>
</div>
</div>
If you have an object like this (which can dynamically change in size / key values)
const values = {
gb: 100,
display: 400,
test: -1200,
best: 500
}
then the total of all values can be calculated dynamically like this:
const total = Object.values(values).reduce((x,y)=>x=+y,0)
For the purpose of understanding, this can be broken down and console.logged like this
const numbers = Object.values(values);
console.log(numbers) // returns [100,400,-1200,500]
const total = numbers.reduce((x,y)=>x=+y,0) // returns total = -200

Checked Check Progress

As you can see above, I have the data I pulled from the database and these are the radio inputs.
Each one has unique database ids and I want to check here with jquery.
For example, if the phone does not select one of the 16GB or 32GB options, I want to give a warning. Since the data coming here comes with a loop, the same thing will enter the loop.
If it is selected, I want to get the values in it.
I would be glad if you could help me.
<form action="" type="POST" onsubmit="return false;">
<div id="form_step_1">
<div class="container">
<div class="row">
<div class="talepler mb-3">
<H4>GB</H4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3 titles">
<input class="inputs" type="radio" id="1" name="1">
<label class="btn btn-pill" style="display: inline-block;">16 GB</label>
<input class="inputs" type="radio" id="2" name="1">
<label class="btn btn-pill" style="display: inline-block;">32 GB</label>
</div>
</div>
<H4>DİSPLAY</H4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3 titles">
<input class="inputs" type="radio" id="3" name="2">
<label class="btn btn-pill" style="display: inline-block;">durable</label>
<input class="inputs" type="radio" id="4" name="2">
<label class="btn btn-pill" style="display: inline-block;">broken</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success" id="gonder">Gönder</button>
</div>
</div>
</div>
</form>
You can count the checked radios
I must suggest you give them better names and IDs
Note I gave the form an ID and removed the return false from the onsubmit
If you want to submit if ok, then my code will work
If you want to ajax the result, move the
e.preventDefault() to the top of the submit event handler
In this update I run over every title and look in the next div for radios.
You can add other elements to each
https://jsfiddle.net/mplungjan/L7nhjo10/
$(function() {
$("#myTable").on("submit", function(e) {
e.preventDefault(); // comment this to submit when ok
let errors = [],
ids = [];
$(".row h4").each(function() {
let title = $(this).text(),
$container = $(this).closest("div"), // parent
$rads = $container.find("[type=radio]");
if ($rads.length > 0) {
let $chosen = $container.find("[type=radio]:checked");
if ($chosen.length === 0) errors.push(title);
else ids.push($chosen.attr("id"));
}
})
if (errors.length > 0) {
e.preventDefault();
alert("Please choose " + errors.join(", "));
} else console.log(ids);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myTable" action="" type="POST" onsubmit="if (!window.__cfRLUnblockHandlers) return false; return false;">
<div id="form_step_1">
<div class="container">
<div class="row">
<div class="talepler mb-3">
<h4>Telefon Hafızası Seçin</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input style="display: none" class="inputs" type="radio" id="1" name="1" value="1">
<label class="btn btn-pill" style="display: inline-block;" for="1">16GB</label>
</div>
</div>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input style="display: none" class="inputs" type="radio" id="2" name="1" value="1">
<label class="btn btn-pill" style="display: inline-block;" for="2">32GB</label>
</div>
</div>
</div>
<div class="talepler mb-3">
<h4>Ekran Durumu Seçin</h4>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input style="display: none" class="inputs" type="radio" id="3" name="2" value="1">
<label class="btn btn-pill" style="display: inline-block;" for="3">Sağlam</label>
</div>
</div>
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3">
<input style="display: none" class="inputs" type="radio" id="4" name="2" value="1">
<label class="btn btn-pill" style="display: inline-block;" for="4">Kırık</label>
</div>
</div>
</div>
<button type="submit" class="btn btn-success" id="gonder">Gönder</button>
</div>
</div>
</div>
</form>
i will make it simple for you !
add a class to the inputs for exemple : storage or space
preview :
<div class="row mb-3" style="display: inline-block">
<div class="col-sm-3 col-md-4 col-lg-3 titles">
<input class="inputs storage" type="radio" id="1" name="1">
<label class="btn btn-pill" style="display: inline-block;">16 GB</label>
<input class="inputs storage" type="radio" id="2" name="1">
<label class="btn btn-pill" style="display: inline-block;">32 GB</label>
</div>
</div>
and then by jquery you can detect selected one:
$('.storage').on('change',function(){
let selected = $('.storage:checked');
console.log(selected.val());
})
and for other inputs the same process
add new class to them exemple : phone-status or somthing else
and keep going 😀

Cannot read property 'value' of null in contrast checker

The only thing that I changed in my code was that I changed the IDs e.g. previewContrast to preview_contrast and I get a Property value null error.
The error shows for the line "var color = colorObjekt.value.replace("#", "");
I would be grateful if someone could find the error in this code.
var textColorContrast = getColor('txtColor');
var bgColorContrast = getColor('bgColor');
var lumi1 = getLumi(textColorContrast);
var lumi2 = getLumi(bgColorContrast);
if (lumi1 !== false && lumi2 !== false) {
txtColor.style.color = '#'+textColorContrast;
bgColor.style.backgroundColor = '#'+bgColorContrast;
var ratio = (Math.max(lumi1, lumi2) + 0.05) / (Math.min(lumi1, lumi2) + 0.05);
contrastText.innerHTML = (Math.round(ratio * 100) / 100) + ':1';
}
function getColor(location) {
var colorObjekt = document.getElementById(location);
var color = colorObjekt.value.replace("#", "");
return color;
}`
Here is the html
<div class="tab-content container-fluid" id="navi_content" role="main">
<div class="tab-pane fade show active" id="post" role="tabpanel" aria-labelledby="post-tab">
<div class="row" role="row">
<h2 role="heading" class="col-10">Input</h2>
<div class="col-2" role="gridcell">
<button type="button" class="btn btn-lg btn-outline-secondary fas fa-info" role="button"
data-toggle="popover" title="Info" data-trigger="focus"
data-content="On this page you can enter a text to display on the LED Scroll Board. You can also change the background and text color as well as the speed and brightness settings in the Settings modal. By selecting the Date or Clock Mode you can post the current date or time on to the board"
data-placement="bottom"></button>
<button type="button" class="btn btn-lg btn-outline-secondary fas fa-cogs" role="button" data-toggle="modal"
title="Settings" data-target="#settings"></button>
</div>
</div>
<form class="text__form" id="form">
<div class="form-row" role="row">
<div class="form-group col-10" role="gridcell">
<label class="text__label" for="text__input" id="input_label">
Your message:
</label>
<input type="text" class="form-control text__input-text" id="text_input"
placeholder="Text input here... :)" role="textbox" aria-required="true" aria-labelledby="input_abel" required>
<p class="text__counter">150 characters left...</p>
</div>
<div class="col-2 text__colorpicker" role="gridcell">
<div class="form-group" role="gridcell">
<label class="text__label" for="text_color" id="text_color_label">Text Color</label>
<input class="text__input-color" type="color" name="textcolor" id="text_color" value="#ff0000"
aria-labelledby="text_color_label">
</div>
</div>
</div>
<div class="card" role="none">
<div class="card-body" role="group">
<h3 class="card-header" role="heading">Modes</h3>
<fieldset class="form-check" id="color_radios">
<legend class="col-form-label text__card-label" id="modes_legend">
Color Modes
</legend>
<div class="row" role="row">
<div class="form-check form-group col-sm-6" role="form">
<input class="form-check-input text__input-radio" type="radio" name="colorMode"
id="rainbow_mode" value="1" role="radio" aria-labelledby="rainbow_label">
<label for="rainbow_mode" class="form-check-label text__card-label" id="rainbow_label">Rainbow
Mode</label>
</div>
<div class="form-check form-group col-sm-6" role="form">
<input class="form-check-input text__input-radio" type="radio" name="colorMode" id="solid_mode"
value="0" role="radio" aria-labelledby="solid_mode_label" aria-checked="true" checked>
<label for="solid_mode" class="form-check-label text__card-label" id="solid_mode_label">Solid
Mode</label>
<div class="form-group" role="form">
<label for="bg_color" id="bg_color_label" aria-label="Background Color"> Color</label>
<input type="color" name="bgColor" id="bg_color" value="#ABCDEF" aria-labelledby="bg_color_label">
</div>
</div>
</div>
</fieldset>

How to hide divs when radio button is checked on page load?

I have an existing jquery code where it hides divs if the radio button is selected. However, when the page loads.. if this radio button is already checked, I want to be able to hide divs without clicking anything.
<script>
$('input[name=resident]').click(function () {
if (this.id == "residentNo") {
$(".d").hide('slow');
$('.d').find('#precinctNum').val('');
$('.d').find('#yearStartedLiving').val('');
} else {
$(".d").show('slow');
$('.d').find('#precinctNum').val('');
$('.d').find('#yearStartedLiving').val('');
}
});
</script>
html form:
<label class="radio-inline"><input type="radio" class = "res" id = "residentYes" name="resident" value="Yes" checked> Yes</label>
<label class="radio-inline"><input type="radio" class = "res" id = "residentNo" name="resident" value="No" > No</label>
<div class="d item form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Precinct Number <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="precinctNum" class="form-control col-md-5 col-xs-12" name="precinctNum" data-validate-length-range="7" required="required" type="number">
</div>
</div>
<div class="d item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Start of Residency (Year) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="yearStartedLiving" name="yearStartedLiving" class="form-control col-md-5 col-xs-12" required="required" data-inputmask="'mask': '9999'">
</div>
</div>
I've been trying for hours and it doesn't seem to work. Your help will be much appreciated!! Thank you!
document.addEventListener("DOMContentLoaded", function(event) { // Will check after DOM is ready
if($('#residentNo').is(':checked')){ // Check if residentNo is checked
toggleDiv("residentNo")
}
});
$('input[name=resident]').click(function () {
toggleDiv(this.id)
})
function toggleDiv(id){
if (id == "residentNo") {
$(".d").hide('slow');
$(".d").find('#precinctNum, #yearStartedLiving, #birthplace, #weight, #height, #income').val('');
} else {
$(".d").show('slow');
$(".d").find('#precinctNum, #yearStartedLiving, #birthplace, #weight, #height, #income').val('');
}
};
JSFIDDLE
NOTE: In this example I have set residentNo to checked to demo it
You can trigger the event click on field of your interest:
$('input[name=resident][value="No"]').trigger('click');
$(function () {
$('input[name=resident]').click(function () {
if (this.id == "residentNo") {
$(".d").hide('slow');
} else {
$(".d").show('slow');
}
$('.d').find('#precinctNum, #yearStartedLiving').val('');
});
$('input[name=resident][value="No"]').trigger('click');
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<label class="radio-inline"><input type="radio" class = "res" id = "residentYes" name="resident" value="Yes" checked> Yes</label>
<label class="radio-inline"><input type="radio" class = "res" id = "residentNo" name="resident" value="No" > No</label>
<div class="d item form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Precinct Number <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="precinctNum" class="form-control col-md-5 col-xs-12" name="precinctNum" data-validate-length-range="7" required="required" type="number">
</div>
</div>
<div class="d item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Start of Residency (Year) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="yearStartedLiving" name="yearStartedLiving" class="form-control col-md-5 col-xs-12" required="required" data-inputmask="'mask': '9999'">
</div>
</div>
You can do it like below. Just add the code in $(document).ready. Hope it helps.
if($('#residentNo').is(':checked')){
$(".d").hide();
$('.d').find('#precinctNum, #yearStartedLiving').val('');
}
$('input[name=resident]').click(function () {
if (this.id == "residentNo") {
$(".d").hide('slow');
$('.d').find('#precinctNum, #yearStartedLiving').val('');
} else {
$(".d").show('slow');
$('.d').find('#precinctNum, #yearStartedLiving').val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="radio-inline"><input type="radio" class = "res" id = "residentYes" name="resident" value="Yes" checked> Yes</label>
<label class="radio-inline"><input type="radio" class = "res" id = "residentNo" name="resident" value="No" > No</label>
<div class="d item form-group" >
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Precinct Number <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="precinctNum" class="form-control col-md-5 col-xs-12" name="precinctNum" data-validate-length-range="7" required="required" type="number">
</div>
</div>
<div class="d item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Start of Residency (Year) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="yearStartedLiving" name="yearStartedLiving" class="form-control col-md-5 col-xs-12" required="required" data-inputmask="'mask': '9999'">
</div>
</div>

Form.Serialize with checkbox array

I'm submitting a form through JQuery by using the form.serialize method. But that same form has an array of checkboxes, which is dynamically genetrated by a PHP function
This is the form:
<form class="form" id="formNewClient" role="form">
<ul class="nav nav-tabs">
<li class="active"><i class="fa fa-user"></i> Dados Cliente</li>
<li><i class="fa fa-phone"></i> Dados Phonepark</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="clientdata">
<div class="row">
<div class="col-md-12">
<div class="page-header"><h3>Dados Pessoais</h3></div>
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="name">Nome Completo:*</label>
<input type="text" name="clientName" class="form-control" placeholder="Nome Completo do Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="email">Email:</label>
<input type="text" name="clientEmail" class="form-control" placeholder="Email Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="addressone">Morada:</label>
<input type="text" name="clientAddressone" class="form-control" placeholder="Morada do Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address2">Morada (cont.):</label>
<input type="text" name="clientAddresstwo" class="form-control" placeholder="Morada do Utilizador (cont.)">
</div>
<div class="form-group col-md-3">
<label for="postalcode">Código Postal:</label>
<input type="text" name="clientCPostal" class="form-control" placeholder="Código Postal">
</div>
<div class="form-group col-md-3">
<label for="city">Localidade:</label>
<input type="text" name="clientCity" class="form-control" placeholder="Localidade">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="clientNif">NIF</label>
<input type="text" name="clientNif" class="form-control " placeholder="NIF">
</div>
<div class="form-group col-md-4">
<label for="clientBirthdate">Data de Nascimento</label>
<div class="form-group">
<div class='input-group date' id='inputendDate' data-date-format="YYYY/MM/DD">
<input type='text' name="clientBirthdate" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
<div class="form-group col-md-4">
<label for="sex">Sexo:</label>
<br>
<label class="radio-inline">
<input type="radio" name="optionsRadioSex" value="M">
Masculino
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadioSex" value="F">
Feminino
</label>
</div>
</div>
</div>
<!--END CLIENTDATA-->
<div class="tab-pane" id="phoneparkdata">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h3>Dados Phonepark</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12"><h4>Documentos:</h4></div>
<div class="form-group col-md-4">
<label for="document">Tipo de Documento:</label>
<select name="documenttype" class="form-control">
<?php selectListDocuments();?>
</select>
</div>
<div class="form-group col-md-4">
<label for="documentNumber">Número do Documento:*</label>
<input type="text" name="documentNumber" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="documentNumber">Número do Documento (Secundário):</label>
<input type="text" name="documentNumberSec" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-12"><h4>Comunicações:</h4></div>
<div class="form-group col-md-4">
<label for="phone1">Telemóvel:*</label>
<input type="text" name="clientPhonePri" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="phone2">Telemóvel Secundário:</label>
<input type="text" name="clientPhoneSec" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<h4>Perfil:</h4>
<label for="profile">Perfil(s) a utilizar:*</label>
<?php
profileCheckBoxes();
?>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="activationDate">Data de Activação:</label>
<div class="form-group">
<div class='input-group date' id='inputactivationDate' data-date-format="YYYY/MM/DD hh:mm">
<input type='text' name="clientActivationTime" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label for="limitDate">Data de Limite:</label>
<div class="form-group">
<div class='input-group date' id='inputendDate' data-date-format="YYYY/MM/DD hh:mm">
<input type='text' name="clientDeactivationTime" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
</div>
</div>
<!--END PHONEPARKDATA-->
</div>
<!--END TAB-CONTENT-->
<div class="row">
<div class="col-md-4 col-lg-4 pull-right">
<button type="submit" class="btn btn-success" name="submitNewClient" id="submitNewClient"><i class="fa fa-plus"></i> Adicionar Cliente</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>
</div>
</div>
</form>
And this is the php function that generates the checkboxes:
function profileCheckBoxes(){
$queryListProfiles = "SELECT * FROM perfil";
$listProfiles = mysqli_query($GLOBALS['dbc'],$queryListProfiles);
$numProfiles = mysqli_num_rows($listProfiles);
if($numProfiles !=""){
while($row = mysqli_fetch_array($listProfiles)){
?>
<label class="checkbox-inline">
<input type="checkbox" value="<?php echo $row['id']?>" name="profiles[]">
<?php echo $row['Nome']; ?>
</label>
<?php
}
}
}
How can I submit the form with form.serialize in Jquery and in the PHP side process the checkbox so I can extract the values from the checkbox array?
This jQuery documentation page explains how to use the serialize function:
http://api.jquery.com/serialize/
If you then pass the output to your php page using POST, in the PHP script the checked values will be stored in $_POST['profiles'] as an array. So to loop through the values of the checked boxes you could use:
foreach ($_POST['profiles'] as $profile) {
//process code here
}
jQuery's form.serialize only pass checksboxes that are checked.
if you want all your checkboxes to get passed to your server consider to generate also hidden inputs to store those values.
I would also change the checkboxes name to "profiles"

Categories

Resources