How to customize key-value pairs when using .serializeArray() Javascript? - javascript

Code example:
$('#simpan').click(function(){
var data = $('.serialize').serializeArray();
console.log(data)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12">
<label><input type="radio" name="perkawinan" id="" class="form-control-sm serialize" value="belum kawin" data-title="Perkawinan"><b> Belum Kawin</b></label> 
<label><input type="radio" name="perkawinan" id="" class="form-control-sm serialize" value="kawin" data-title="Perkawinan"><b> Kawin</b></label> 
<label><input type="radio" name="perkawinan" id="" class="form-control-sm serialize" value="duda/janda" data-title="Perkawinan"><b> Duda/Janda</b></label> 
<label><input type="radio" name="perkawinan" id="" class="form-control-sm serialize" value="bawah umur" data-title="Perkawinan"><b> Bawah Umur</b></label> 
</div>
</div>
<div class="row">
<div class="col-lg-12">
<input type="text" name="pekerjaan" id="" class="form-control form-control-sm serialize" placeholder="Pekerjaan..." data-title="Pekerjaan">
</div>
</div>
<div class="row">
<button type="button" class="btn btn-sm btn-outline-success" id="simpan">SIMPAN</button>
</div>
The result will be an array of object with key->value pairs of name and value. How to add additional key when we execute .serializeArray()?
The desired output is :
[
{
"name": "perkawinan",
"value": "kawin",
"title": "Status Perkawinan",
"type": "radio"
},
{
"name": "pekerjaan",
"value": "",
"title": "Pekerjaan Pasien",
"type": "text"
}
]

Sorry for the late reply, was busy with sme works... You can do this in two way
HTML
<div class="container">
<div class="row">
<form action="" method="post" enctype="multipart/form-data" class="serialize">
<div clas="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" name="perkawinan" class="custom-control-input" value="Belum Kawin" data-title="Title 1">
<label class="custom-control-label" for="customRadioInline1">Belum Kawin</label>
<input type="radio" name="perkawinan" class="custom-control-input" value="Duda/Janda" data-title="Title 2">
<label class="custom-control-label" >Duda/Janda</label>
</div>
<div class="form-group" style="margin:15px 0">
<label>Pekerjaan</label>
<input type="text" name="pekerjaan" class="form-control" placeholder="Pekerjaan" data-title="Title 3">
</div>
</div>
<div clas="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<input name="submit" type="button" value="Submit" id="simpan" class="btn btn-success">
</div>
</form>
<div clas="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="output" style="margin-top:20px"></div>
</div>
</div>
Method 1
This will return the object even if the text box value is null
<script type="text/javascript">
$(function()
{
$('#simpan').on('click',function()
{
var data = $('.serialize :input').serializeArray();
var data = $.each(data, function(i,obj){obj.title = $("input[name='"+obj['name']+"']").data('title');obj.type = $("input[name='"+obj['name']+"']").attr('type');});
$('#output').html(JSON.stringify(data))
})
});
</script>
Method 2
This will return objects which have values
<script type="text/javascript">
$(function()
{
$('#simpan').on('click',function()
{
var data = $( ".serialize :input").filter(function () {return !!this.value;}).serializeArray();
var data = $.each(data, function(i,obj){obj.title = $("input[name='"+obj.name+"']").data('title');obj.type = $("input[name='"+obj.name+"']").attr('type');});
$('#output').html(JSON.stringify(data))
})
});
</script>
here is a working fiddle JSFiddle

Related

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 😀

Submit a form in the background with ajax

I have the following problem, I am using Prestashop and I need a form to make a submit in the background, I have investigated and I found a way to do it with ajax but I need the url and data parameter that I do not know how to get them since the form is this.
As you can see, the form has no action and the data is not clearly visible, this would be the way I have in mind to do it with ajax:
$(document).ready(function() {
$("#makePdfCatalogue").submit(function(e) {
e.preventDefault();
var dataString = $("#makePdfCatalogue").serialize(); //this way i cant get the data
console.log(dataString);
$.ajax({
type: "POST",
url: "", //action doenst appear
data: dataString,
success: function(msg) {
console.log('working: ' + msg);
},
error: function(msg) {
//console.log('not working ' + msg);
}
});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="makePdfCatalogue" name="makePdfCatalogue" method="POST" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6">
<fieldset>
<legend>Categorías</legend>
<div class="form-group">
<label class="" for="name">{l s="Selecciona la categoría/s que deseas exportar" mod="custompdfexport"}</label> {$categories_tree}
</div>
</fieldset>
</div>
<div class="col-md-6">
<fieldset>
<legend>Datos empresa</legend>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="" for="name">Nombre Empresa</label>
<input type="text" name="name" placeholder={l s="Nombre Empresa..." mod="custompdfexport" } class="form-control" id="name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="" for="contact">Datos contacto</label>
<input type="text" name="contact" placeholder={l s="Datos Contacto..." mod="custompdfexport" } class="form-control" id="contact">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="" for="logo">Logo empresa</label>
<input type="file" name="logo" placeholder={l s="logo Empresa..." mod="custompdfexport" } class="form-control" id="logo">
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Opciones</legend>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label class="" for="form-password">{l s="Diseño" mod="custompdfexport"}</label>
<ul>
<li>
<input type="radio" name="format" class="form-control" value="2" id="format-2"><label for="format-2">{l s="2 columnas" mod="custompdfexport"}</label>
</li>
<li>
<input type="radio" name="format" class="form-control" value="3" id="format-3"><label for="format-3">{l s="3 columnas" mod="custompdfexport"}</label>
</li>
<li>
<input type="radio" name="format" class="form-control" value="4" id="format-4"><label for="format-4">{l s="4 columnas" mod="custompdfexport"}</label>
</li>
</ul>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label class="" for="form-password">Opciones</label>
<div class="form-group"><input type="checkbox" name="options[]" class="form-control" id="opt-wt" value="wt"><label for="opt-wt">{l s="Mostrar Precios con Iva" mod="custompdfexport"}</label></div>
<div class="form-group"><input type="checkbox" name="options[]" class="form-control" id="opt-wot" value="wot"><label for="opt-wot"> {l s="Mostrar Precios sin Iva" mod="custompdfexport"}</label></div>
<div class="form-group"><input type="checkbox" name="options[]" class="form-control" id="opt-ref" value="reference"><label for="opt-ref">{l s="Mostrar referencia" mod="custompdfexport"}</label></div>
<div class="form-group"><input type="checkbox" name="options[]" class="form-control" id="opt-link" value="link"><label for="opt-link">{l s="Enlazar productos con web" mod="custompdfexport"}</label></div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="" for="revenue">Margen comercial (%)</label>
<input type="text" name="revenue" placeholder={l s="Margen comercial..." mod="custompdfexport" } class="form-control" id="revenue" style="width: 100px;">
</div>
<div class="form-group">
<label class="" for="revenue">Descuento (%)</label>
<input type="text" name="reduction" placeholder={l s="Descuento..." mod="custompdfexport" } class="form-control" id="reduction" style="width: 100px;">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="" for="form-password">Ordenar</label>
<div class="form-group"><input type="radio" name="order" class="form-control" id="order-asc" value="price_asc"><label for="order-asc">{l s="Por precio de Menor a Mayor" mod="custompdfexport"}</label></div>
<div class="form-group"><input type="radio" name="order" class="form-control" id="order-desc" value="price_desc"><label for="order-desc">{l s="Por precio de Mayor a Menor" mod="custompdfexport"}</label></div>
</div>
<div class="col-md-6">
<label class="" for="form-password">Stock</label>
<div class="form-group"><input type="checkbox" name="stock" class="form-control" id="stock" value="stock"><label for="stock">{l s="Seleccionar sólo artículos con stock"}</label></div>
</div>
</div>
</fieldset>
<br>
<input type="hidden" name="token" value="{$token|escape:'html':'UTF-8'}" />
<input type="submit" name="submitMakePdfCatalogue" id="submitMakePdfCatalogue" value="{l s='Generar' mod='custompdfexport'}" class="exclusive" />
</div>
</div>
</form>
any suggestion of how to get those parameters...
I already solved the data problem and I also know that the action is catalogue.php but I don't know how to locate it with the url since it is inside a prestashop module. I tried something like that but it gave me an error 500 that is, it is not the correct path
$(document).ready(function() {
$("#makePdfCatalogue").submit(function(e) {
e.preventDefault();
var dataString = $("#makePdfCatalogue").serialize(); //solved
$.ajax({
type: "POST",
headers: { "cache-control": "no-cache" },
url: baseDir + 'modules/custompdfexport/controllers/front/catalogue.php',//is not the correct url
data: dataString,
success: function(msg) {
console.log('working: '+msg);
},
error: function(msg) {
console.log('not working '+msg);
}
});
})
})
This is how you can get a link to your controller:
Context::getContext()->link->getModuleLink('custompdfexport', 'catalogue');
In your case you are calling controller via AJAX so you need pass the ajax parameter in url like this:
Context::getContext()->link->getModuleLink('custompdfexport', 'catalogue', array('ajax' => true));
If you have URL rewriting enabled your URL will look something like:
http://<shop_domain>/en/module/custompdfexport/catalogue?ajax=true
Source

Generateing dynamic id attribute for radio and checkboxes in vue

I am adding a vue component on button click. Its adding new form element with checkbox and radio button which contain id with for element of . How to assign a new Id to checkboxes and radio buttons every time I add a new component.
I tried passing numeric values to the id and for attributes but it doesn't work
Vue.component('persons-phone', {
props: ['index'],
template: `
<div class="row person_phone_wrapper">
<div class="col-md-4">
<div class="form-group">
<label for="person_phone">Phone Number : <span class="danger">*</span></label>
<input type="tel" class="form-control required" name="person_phone[]">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="c-inputs-stacked">
<br><br>
<input type="checkbox" id="verified_number_#{{ index }}" name="verified_phone[]">
<label for="verified_number_#{{ index }}" class="block">Verified</label>
</div>
</div>
</div>
<div class="col-md-4">
<div>
<br><br>
<input name="phone_status[]" type="radio" class="with-gap" id="radio_#{{ index }}" />
<label for="radio_#{{ index }}">Active</label>
<input name="phone_status[]" type="radio" class="with-gap" id="radio_#{{ index + 1 }}"/>
<label for="radio_#{{ index + 1 }}">Inactive</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="remove_person_phone"> </label><br>
<button type="button" class="btn btn-danger btn-sm" #click="$emit('remove')">
<i class="fa fa-close"></i> Remove
</button>
</div>
</div>
</div>
`,
})
var app = new Vue ({
el: '#app',
data: {
personsPhoneCount: [1],
currentPhoneIndex: 1
},
methods: {
deletePersonsPhone: function(index){
this.personsPhoneCount.splice(index,1)
},
addPersonsPhone: function(){
index = this.currentPhoneIndex + 1;
this.currentPhoneIndex = index;
this.personsPhoneCount.push(index);
}
},
computed: {
}
})
<persons-phone v-for="(pPC, index) in personsPhoneCount" #remove="deletePersonsPhone(index)" :num="currentPhoneIndex">
</persons-phone>
Doing this solved my problem
Vue.component('persons-phone', {
props: {
index: {
type: Number,
required: true
},
},
template: `
<div class="row person_phone_wrapper">
<div class="col-md-4">
<div class="form-group">
<label for="person_phone">Phone Number: <span class="danger">*</span></label>
<input type="tel" class="form-control required" name="person_phone[]">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="c-inputs-stacked">
<br><br>
<input type="checkbox" :id="checkbox" name="verified_phone[]">
<label :for="checkbox" class="block">Verified</label>
</div>
</div>
</div>
<div class="col-md-4">
<div>
<br><br>
<input :name="radio" type="radio" class="with-gap" :id="radio1" />
<label :for="radio1">Active</label>
<input :name="radio" type="radio" class="with-gap" :id="radio2"/>
<label :for="radio2">Inactive</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="remove_person_phone"> </label><br>
<button type="button" class="btn btn-danger btn-sm" #click="$emit('remove')">
<i class="fa fa-close"></i> Remove
</button>
</div>
</div>
</div>
`,
data: function() {
return {
radio: 'phone_status['+this.index+']',
radio1: 'radio_' + this.index,
radio2: 'radio_' + this.index + '_' + this.index,
checkbox: 'verified_number_'+ this.index,
}
}
})

Show hidden fields when checkbox is checked?

Hi I have multiple checkboxes of similar kind. I am applying javascript on the checkbox to show hidden fields. I have created a js code which works for a single checkbox, I want to apply a code that will work for all checkboxes.
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox" type="checkbox">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox" type="checkbox">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
JS Code :-
var checkbox = document.getElementById('checkbox');
var box = document.getElementById('box');
checkbox.onclick = function() {
console.log(this);
if (this.checked) {
box.style['display'] = 'block';
} else {
box.style['display'] = 'none';
}
};
Now the thing is i can make individual javascript for all checkboxes but that will contain numerous js code, I want that a single javascript function can unhide the elements from every checkbox when clicked. A single js code should work for all checkboxes. Kindly please provide a way of doing it with plain javascript or jquery.
Try this
on your check box's onchange event call function onchange="showHiddenField(this)"
and function is like
function showHiddenField(currentObject) {
var inputDiv = $(currentObject).parent().next();
if ($(currentObject).is(":checked")) {
$(inputDiv).show().focus();
}
else {
$(inputDiv).hide();
}
}
Use javascript function to make it.
function toggleFields(boxId, checkboxId) {
var checkbox = document.getElementById(checkboxId);
var box = document.getElementById(boxId);
checkbox.onclick = function() {
console.log(this);
if (this.checked) {
box.style['display'] = 'block';
} else {
box.style['display'] = 'none';
}
};
}
toggleFields('box1', 'checkbox1');
toggleFields('box2', 'checkbox2');
<link href="//cdn.bootcss.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<!--<input id="checkbox" type="checkbox">-->
<input id="checkbox1" type="checkbox">
</div>
<!--<div class="col-md-4" id="box" style="display: none;">-->
<div class="col-md-4" id="box1" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<!--<input id="checkbox" type="checkbox">-->
<input id="checkbox2" type="checkbox">
</div>
<!--<div class="col-md-4" id="box" style="display: none;">-->
<div class="col-md-4" id="box2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
Okay this is how this works, each checkbox will have the id of its box as a class, so that when ever that checkbox is clicked, we will use its class to make its box visible. This will work even if you have 1000 checkboxes
var checkbox = document.querySelectorAll("#check1, #check2");
for (i = 0; i < checkbox.length; i++) {
checkbox[i].onclick = function() {
if (this.checked) {
document.getElementById(this.getAttribute('class')).style['display'] = 'block';
} else {
document.getElementById(this.getAttribute('class')).style['display'] = 'none';
}
};
}
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check1" type="checkbox" class="box">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check2" type="checkbox" class="box2">
</div>
<div class="col-md-4" id="box2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
Yes you can do this. Solution in below code. i did this using JQuery.
$('input[type="checkbox"]').click(function(){
console.log(this);
// $(this).parent().next().css('display','block');
$(this).parent().next().toggle('show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input name="chkbox" type="checkbox">
</div>
<div class="col-md-4" data-box="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input name="chkbox" type="checkbox">
</div>
<div class="col-md-4" data-box="box" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
First Please note down in your mind "id" is only apply on a single elemnt on each page for multiple element you can apply a "class"
id="checkbox" replace with class="checkbox"
in Jquery
$(document).ready(function(){
$(".checkbox").change(function(){
if($(this).prop("checked")){
$(this).parents(".row").find(".box").show();
}else{
$(this).parents(".row").find(".box").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input class="checkbox" type="checkbox">
</div>
<div class="col-md-4 box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input class="checkbox" type="checkbox">
</div>
<div class="col-md-4 box" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
You can use querySelectorAll("[type='checkbox']") to select all checkbox and iterate through the elements using for loop.
Note : The id should be unique for each element.
var checkbox = document.querySelectorAll("[type='checkbox']");
for (i = 0; i < checkbox.length; i++) {
checkbox[i].onclick = function() {
if (this.checked) {
document.getElementById(this.getAttribute('class')).style['display'] = 'block';
} else {
document.getElementById(this.getAttribute('class')).style['display'] = 'none';
}
};
}
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check1" type="checkbox" class="box">
</div>
<div class="col-md-4" id="box" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="check2" type="checkbox" class="box2">
</div>
<div class="col-md-4" id="box2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
The most narrowed (static) suggestion from your code:
$(document).ready(function() {
$('input[type=checkbox]').change(function(){
if($(this).prop('checked')){
$(this).parent().next().show();
}else{
$(this).parent().next().hide();
}
});
});
Use class attribute to get dynamic process.
Tested on google Chrome works.
gets id of input takes the number after "checkbox(gets_target)" string. creates a id with adding this number to end of "box"+number string
HTML :
<input onChange="display_hidden_field(this)" id="checkbox2" type="checkbox">
<div id="box2" style="display:none;">content</div>
Javascript :
function display_hidden_field(checkbox){
var box_id = checkbox.id;
var search_pattern = /checkbox(.*?)$/g;
var number = search_pattern.exec(box_id);
number = number[1];
box_id = 'box'+number;
var box = document.getElementById(box_id);
if(checkbox.checked){
box.style.display = 'block';
}else{
box.style.display = 'none';
}
}
You can use code like this what i did in this your every checkbox id create like this "checkbox_1" and your box id like this box_1 and so on other numbers please check below code you will get idea what you need to do with your html and java script.
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox_1" type="checkbox" onclick="myfunction(this);">
</div>
<div class="col-md-4" id="box_1" style="display: none;">
<input type="number" name="practical1" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-2">
<label>Practical Course:</label>
<input id="checkbox_2" type="checkbox" onclick="myfunction(this);">
</div>
<div class="col-md-4" id="box_2" style="display: none;">
<input type="number" name="practical2" class="form-control">
</div>
</div>
</div>
</div>
<script>
function myfunction(obj)
{
var element_index = obj.id.split("_");
console.log('box_'+element_index[1]);
var box = document.getElementById('box_'+element_index[1]);
if(obj.checked) {
box.style['display'] = 'block';
} else {
box.style['display'] = 'none';
}
}
</script>
Here in script i have given function name myfunction but you can set your function name as per your need. may this is helpful for you.

How to drop empty elements and their keys in a JavaScript object?

I get objects of the type of:
{
personalData: {
name: "Diego",
last: "Aguilar",
mail: "diego#domain.com"
},
professionalData: {
almaMater: "BUAP",
courses: [
{},
{
name: "JavaScript Newbies",
tags: ["","",""]
}
]
}
}
So in that example, empty objects at professionalData.courses should be dropped and so the tags key at second object as their array elements are whole empty ones.
In general words, any time I find values being an empty object or array element, drop them. Also, if a key would get empty arrays or objects, drop them too.
Maybe jQuery or lodash/underscore would give a direct solution to this?
This is an example of an object stored at MongoDB:
{
"_id" : ObjectId("537e09c9896e05225cf50cb8"),
"datosPersonales" : {
"name" : "Maricela",
"lastname" : "Aguilar Flores",
"age" : "22",
"phone" : "2878710097",
"mobile" : "2878812505",
"email" : "af05_#hotmail.com",
"address" : "Carranza 168 Int 2"
},
"datosProfesionales" : {
"postgraduates" : [
{
"degree" : "Especialidad",
"title" : "Amor",
"cedula" : "ASFAS5"
},
{
"degree" : "Maestría",
"title" : "Romance",
"cedula" : "v"
}
],
"works" : [
"Universidad Hispano"
],
"freelances" : [ ],
"noPsychoWorks" : [ ],
"almaMater" : "BUAP",
"course" : "1987",
"cedula" : "SAFS555FSA",
"workAreas" : [
"Clínica",
"Laboral"
],
"freelance" : "true",
"noPsychoWork" : "false"
},
"interesesProfesionales" : {
"groups" : [
"Asociación de Psicólogos de Tuxtepec",
"Club de Toby"
],
"trainingTopics" : [
"Real Madrid",
"Cocina"
],
"belongsToSomewhere" : "true",
"activities" : [
"Conferencias y encuentros",
"Talleres"
],
"trainingAreas" : [
"Educativa"
],
"hasParticipated" : "true",
"wantsToBelong" : "true",
"whyToBelong" : "Futuro"
}
}
EDIT
This ugly objects are result of a bad handling in my Angular module.
That object came as a result of this code at Angular controller:
(function() {
var app = angular.module('PsicologosRegister', ['checklist-model'])
app.controller('PsicologoController', function($scope) {
this.psycho = psicologo
this.print = function() {
console.log(this.psycho)
}
this.toMongo = function() {
$.ajax({
type:"POST",
url:"/psychos",
data:this.psycho
})
}
})
app.controller('PersonalDataController', function() {
this.data = datos_Personales
})
app.controller('ProfessionalDataController', function() {
this.data = datos_Profesionales
})
app.controller('ProfessionalInterestsController', function() {
this.data = intereses_Profesionales
this.print = function() {
console.log(this.psycho)
}
})
app.controller('PosgraduateController', function() {
this.degrees = [
'Especialidad',
'Maestría',
'Doctorado'
]
this.postgraduates = _postgraduates
this.addPostgraduate = function() {
this.postgraduates.push({})
}
})
app.controller('WorkController', function() {
this.works = _works
this.addWork = function() {
this.works.push("")
}
})
app.controller('FreelanceController', function() {
this.freelances = _freelances
this.addFreelance = function() {
this.freelances.push("")
}
this.noFreelance = function() {
this.freelances = [""]
}
})
app.controller('NoPsychoWorkController', function() {
this.noPsychoWorks = _noPsychoWorks
this.addNoPsychoWork = function() {
this.noPsychoWorks.push("")
}
this.notNoPsychoWorks = function() {
this.noPsychoWorks = [""]
}
})
app.controller('TrainingTopicsController', function() {
this.trainingTopics = _trainingTopics
this.add = function() {
this.trainingTopics.push("")
}
})
app.controller('GroupsController', function() {
this.groups = _groups
this.add = function() {
this.groups.push("")
}
this.doesntBelongToAnywhere = function() {
this.groups = [""]
}
})
var _noPsychoWorks = [""]
var _freelances = [""]
var _works = [""]
var _postgraduates = [{}]
var _trainingTopics = [""]
var _groups = [""]
var _events = [{}]
var datos_Personales = {}
var datos_Profesionales = {postgraduates:_postgraduates, works: _works, freelances:_freelances, noPsychoWorks:_noPsychoWorks}
var intereses_Profesionales = {events:_events,groups:_groups,trainingTopics:_trainingTopics}
var psicologo = {
datosPersonales: datos_Personales,
datosProfesionales: datos_Profesionales,
interesesProfesionales: intereses_Profesionales
}
})()
This data is generated with the inputs from a web form, rendered with Angular. For elements at arrays I use ng-repeat. The problem is that as it's unknown whether there will be any freelances, postgraduates, etc. I start their belonging keys with Strings, for example.
This is my whole long markup:
<div id="formulario">
<div class="container" id="seccionRegistro1" ng-controller="PersonalDataController as personal">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputNombre" class="col-xs-2 control-label">Nombre(s)</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Nombre(s)" ng-model="personal.data.name" >
</div>
</div>
<div class="form-group">
<label for="inputApellidos" class="col-xs-2 control-label">Apellidos</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Apellidos" ng-model="personal.data.lastname">
</div>
</div>
<div class="form-group">
<label for="inputEdad" class="col-xs-2 control-label">Edad</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Edad" ng-model="personal.data.age">
</div>
</div>
<div class="form-group">
<label for="inputTel" class="col-xs-2 control-label">Teléfono</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Teléfono" ng-model="personal.data.phone">
</div>
</div>
<div class="form-group">
<label for="inputCel" class="col-xs-2 control-label">Celular</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Celular" ng-model="personal.data.mobile">
</div>
</div>
<div class="form-group">
<label for="inputMail" class="col-xs-2 control-label">e-mail</label>
<div class="col-xs-10">
<input type="email" class="form-control" placeholder="e-mail" ng-model="personal.data.email">
</div>
</div>
<div class="form-group">
<label for="inputFB" class="col-xs-2 control-label">Facebook</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Facebook" ng-model="personal.data.fb">
</div>
</div>
<div class="form-group">
<label for="inputDireccion" class="col-xs-2 control-label">Dirección</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Dirección" ng-model="personal.data.address">
</div>
</div>
<div class="col-xs-offset-2 col-xs-10">
<input type="button" class="btn btn-primary btnSeccion" id="btnSeccion1" value="Continuar"/>
</div>
</form>
</div>
<div class="container" id="seccionRegistro2" ng-controller="ProfessionalDataController as professional">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputAlmaMater" class="col-xs-2 control-label">Egresado de</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Egresado de" ng-model="professional.data.almaMater">
</div>
</div>
<div class="form-group">
<label for="inputAñoEgreso" class="col-xs-2 control-label">Año de egreso</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Año de egreso" ng-model="professional.data.course">
</div>
</div>
<div class="form-group">
<label for="inputCedula" class="col-xs-2 control-label">Cédula Profesional</label>
<div class="col-xs-10">
<input type="text" class="form-control" placeholder="Cédula Profesional" ng-model="professional.data.cedula">
</div>
</div>
<div class="form-group" ng-controller="PosgraduateController as postgraduate">
<label for="checkPosgrado" class="col-xs-2 control-label">Estudios de Posgrado</label>
<div ng-repeat="p in postgraduate.postgraduates track by $index">
<div class="padding-between-lines">
<label for="checkPosgrado" class="col-xs-2 control-label" ng-show="$index!=0"></label>
<div class="col-xs-2">
<select ng-options="t for t in postgraduate.degrees" ng-model="p.degree" class="form-control"><select>
</div>
<div class="col-xs-4">
<input type="text" ng-model="p.title" class="form-control inputPosgradoTitulo" placeholder="Título">
</div>
<div class="col-xs-3">
<input type="text" ng-model="p.cedula" class="form-control inputPosgradoCedula" placeholder="Cédula">
</div>
<div class="col-xs-1">
<input type="button" class="form-control" value="Añadir" ng-click="postgraduate.addPostgraduate()" ng-show="$index==0">
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="areaTrabajo" class="col-xs-2 control-label">Areas de la psicología en las que se desempeña</label>
<div class="col-xs-10" >
<label class="checkbox-inline" ng-repeat="area in ['Clínica', 'Social', 'Laboral', 'Educativa']">
<input type="checkbox" checklist-model="professional.data.workAreas" checklist-value="area"> {{area}}
</label>
</div>
</div>
<div class="form-group" ng-controller="WorkController as work">
<label for="inputTrabajo" class="col-xs-2 control-label">Institución de trabajo</label>
<div ng-repeat="w in work.works track by $index">
<div class="padding-between-lines">
<label for="inputTrabajo" class="col-xs-2 control-label" ng-show="$index!=0"></label>
<div class="col-xs-9">
<input type="text" class="form-control" placeholder="Institución de trabajo" ng-model="work.works[$index]">
</div>
<div class="col-xs-1">
<input type="button" class="form-control" value="Añadir" ng-click="work.addWork()" ng-show="$index==0">
</div>
</div>
</div>
</div>
<div class="form-group" ng-controller="FreelanceController as freelance">
<label for="trabajoIndependiente" class="col-xs-2 control-label">Desarrollo Profesional Independiente</label>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" ng-model="professional.data.freelance" name="optionsTrabajoIndependiente" value="true">
Sí
</label>
</div>
</div>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" ng-model="professional.data.freelance" ng-change="freelance.noFreelance()" name="optionsTrabajoIndependiente" value="false">
No
</label>
</div>
</div>
<div ng-repeat="f in freelance.freelances track by $index">
<div class="padding-between-lines">
<label class="col-xs-4" ng-hide="$index==0"></label>
<div class="col-xs-7">
<input type="text" class="form-control" placeholder="Desarrollo profesional independiente" ng-model="freelance.freelances[$index]" ng-disabled="professional.data.freelance=='false'">
</div>
<div class="col-xs-1">
<input type="button" class="form-control añadirTrabajoIndependiente" value="Añadir" ng-show="$index==0" ng-click="freelance.addFreelance()" ng-disabled="professional.data.freelance=='false'">
</div>
</div>
</div>
</div>
<div class="form-group" ng-controller="NoPsychoWorkController as noPsycho">
<label class="col-xs-2 control-label">Actividades de trabajo no relacionadas con la psicología</label>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" ng-model="professional.data.noPsychoWork" name="optionsTrabajoNoPsicologia" value="true">
Sí
</label>
</div>
</div>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" ng-model="professional.data.noPsychoWork" name="optionsTrabajoNoPsicologia" value="false" ng-change="noPsycho.notNoPsychoWorks()">
No
</label>
</div>
</div>
<div ng-repeat="n in noPsycho.noPsychoWorks track by $index">
<div class="padding-between-lines">
<label class="col-xs-4" ng-hide="$index==0"></label>
<div class="col-xs-7">
<input type="text" class="form-control" placeholder="Actividad" ng-model="noPsycho.noPsychoWorks[$index]" ng-disabled="professional.data.noPsychoWork=='false'">
</div>
<div class="col-xs-1">
<input type="button" class="añadirTrabajoNoPsicologia form-control" value="Añadir" ng-show="$index==0" ng-click="noPsycho.addNoPsychoWork()" ng-disabled="professional.data.noPsychoWork=='false'">
</div>
</div>
</div>
</div>
<div class="col-xs-offset-2 col-xs-10" ng-controller="PsicologoController as psi">
<input type="button" class="btn btn-primary btnSeccion" id="btnSeccion2" value="Continuar" ng-click="psi.print()"/>
</div>
</form>
</div>
<div class="container" id="seccionRegistro3" ng-controller="ProfessionalInterestsController as interests">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="actividadesInteres" class="col-xs-2 control-label">Actvidades profesionales en las que le gustaría participar</label>
<div class="col-xs-10" >
<label class="checkbox-inline" ng-repeat="area in ['Conferencias y encuentros', 'Cursos', 'Talleres', 'Diplomados', 'Maestría', 'Doctorado']">
<input type="checkbox" class="areaTrabajo" checklist-model="interests.data.activities" checklist-value="area"> {{area}}
</label>
</div>
</div>
<div class="form-group">
<label for="capacitacionInteres" class="col-xs-2 control-label">Areas de la psicología en las que le gustaría capacitarse</label>
<div class="col-xs-10">
<label class="checkbox-inline" ng-repeat="area in ['Clínica', 'Social', 'Laboral', 'Educativa']">
<input type="checkbox" class="areaTrabajo" checklist-model="interests.data.trainingAreas" checklist-value="area"> {{area}}
</label>
</div>
</div>
<div class="form-group" ng-controller="TrainingTopicsController as trainingTopic">
<label for="inputNombre" class="col-xs-2 control-label">¿Alguna temática en particular que le gustaría conocer o capacitarse?</label>
<div ng-repeat="tp in trainingTopic.trainingTopics track by $index">
<div class="padding-between-lines">
<label class="col-xs-2 control-label" ng-hide="$index==0"></label>
<div class="col-xs-9">
<input type="text" class="form-control" placeholder="Temática de interés" ng-model="trainingTopic.trainingTopics[$index]">
</div>
<div class="col-xs-1">
<input type="button" class="añadirTemaInteres form-control" value="Añadir" ng-show="$index==0" ng-click="trainingTopic.add()">
</div>
</div>
</div>
</div>
<div class="form-group" ng-controller="GroupsController as group">
<label for="checkPosgrado" class="col-xs-2 control-label">¿Pertenece a alguna agrupación relacionada con el campo de la psicología?</label>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" name="optionsPertenenciaAgrupacion" value="true" ng-model="interests.data.belongsToSomewhere">
Sí
</label>
</div>
</div>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" name="optionsPertenenciaAgrupacion" value="false" ng-model="interests.data.belongsToSomewhere" ng-change="group.doesntBelongToAnywhere()">
No
</label>
</div>
</div>
<div ng-repeat="g in group.groups track by $index">
<div class="padding-between-lines">
<label class="col-xs-2 control-label" ng-hide="$index==0"></label>
<div class="col-xs-7">
<input type="text" class="inputAgrupacion form-control" placeholder="Agrupación" ng-model="group.groups[$index]" ng-disabled="interests.data.belongsToSomewhere=='false'">
</div>
<div class="col-xs-1">
<input type="button" class="form-control" value="Añadir" ng-show="$index==0" ng-click="group.add()" ng-disabled="interests.data.belongsToSomewhere=='false'">
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="participacionEventos" class="col-xs-2 control-label">¿Ha participado con anterioridad en algún evento de la Asociación de Psicólogos de Tuxtepec?</label>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" name="optionsParticipacionEventos" value="true" ng-model="interests.data.hasParticipated">
Sí
</label>
</div>
</div>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" name="optionsParticipacionEventos" value="false" ng-model="interests.data.hasParticipated">
No
</label>
</div>
</div>
<div class="col-xs-8">
<select multiple class="form-control">
<option value="abrazoterapia">Abrazoterapia</option>
<option value="tallerMujeres">Taller autoestima mujeres</option>
</select>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<h4>Le gustaría participar como miembro activo de la Asociación de Psicólogos de Tuxtepec A.C</h4>
</div>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" name="optionsMiembro" value="true" ng-model="interests.data.wantsToBelong">
Sí
</label>
</div>
</div>
<div class="col-xs-1">
<div class="radio">
<label>
<input type="radio" name="optionsMiembro" value="false" ng-model="interests.data.wantsToBelong">
No
</label>
</div>
</div>
<div class="col-xs-4">
<textarea class="form-control" rows="3" placeholder="¿Por qué?" ng-model="interests.data.whyToBelong"></textarea>
</div>
</div>
<div class="col-xs-offset-2 col-xs-10" ng-controller="PsicologoController as psi">
<input type="button" class="btn btn-primary btnSeccion" id="btnSeccion3" value="Finalizar" ng-click="psi.toMongo()"/>
</div>
</form>
</div>
</div>
Why not just keep it simple and create a solution that works for the given object. You can always refactor it and then come up with a more elegant solution after that. But you'll need to establish a working point just to get you started. I'd also suggestion caution to creating a complex solution too - because after all, schemas can change ( no matter how many times you may be told they won't ).
I'd start out by just creating separate methods to evaluate each piece individually. For instance, create a solution to work with each of your parent keys ( datosPersonales, datosProfesionales, interesesProfesionales ) that will just determine if they are empty first.
Next, create a solution to work with each sibling of those parents ( postgraduates would have its own routine to check for empty values, works would have its own, etc. ).
Follow this for each branch in the object.
Once you get something that can evaluate each one of them, you'll then be able to start refactoring by working your way up from the bottom-most level ( for instance, tags would be the bottom most level in your first object example ).
Start combining like methods that seem to do the same job and create a universal method that works for each like structure.
And so on..
Once you get a solution close to what you want, I think that's when you'll either be ready to say "hey, can someone help me refactor this even more?".
A good utility kit to help you on your way is underscore: http://underscorejs.org/#map
hope that helps.

Categories

Resources