javascript getElementById start with - javascript

I want to select div start with * to change it from display: block to display:hidden
function select_to_text(a) {
var as = '#' + a;
var aa = $(as).val();
if (aa == "0") {} else {
//var $eles = $(":*[name^='personal_family_type_']").css("background-color","yellow");
document.getElementById(a + "_" + aa + "_block").style.display = 'block';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="personal_family_type" class="control-label col-sm-2">type</label>
<div class="col-sm-10">
<select size="1" id="personal_family_type" name="personal_family_type" class="form-control btn btn-primary" onchange="select_to_text('personal_family_type')">
<option value="0">----</option>
<option value="wife">Wife</option>
<option value="husband">Husband</option>
<option value="son">Son</option>
<option value="all">Show all</option>
</select>
<div id="personal_family_type_wife_block" style="display :none">
wife
</div>
<div id="personal_family_type_husband_block" style="display :none">
husband
</div>
<div id="personal_family_type_son_block" style="display :none">
son
</div>
</div>
</div>

you should not pass in params to your onchange handler -- you can get more flexibility if you tap into the event callback stuff via javascript. I'd also utilize classes to find your elements of interest...there are ways to make the selector more efficient, but to illustrate the point, I'm keeping it simple.
to start -- replace some of the encoded information from the id of the divs with class names and remove the onchange property.
<div class="form-group">
<label for="personal_family_type" class="control-label col-sm-2">type</label>
<div class="col-sm-10">
<select size="1" id="personal_family_type" name="personal_family_type" class="form-control btn btn-primary" >
<option value="0">----</option>
<option value="wife">Wife</option>
<option value="husband">Husband</option>
<option value="son">Son</option>
<option value="all">Show all</option>
</select>
<div id="wife_block" class="personal_family_type" style="display :none">
wife
</div>
<div id="husband_block" class="personal_family_type" style="display :none">
husband
</div>
<div id="son_block" class="personal_family_type" style="display :none">
son
</div>
</div>
</div>
next, bind your select element to the onchange handler and then the logic in select_to_text, in a nutshell:
set all elements to display:none, then set the specific elements to display:block per the settings (I'm assuming I understand the way this is supposed to work).
script:
$('#personal_family_type').on('change',select_to_text);
function select_to_text(evt) {
var $blocks;
$blocks = $('.'+evt.target.id).hide();
switch (evt.target.value) {
case '0':
break;
case 'all':
$blocks.show();
break;
default:
$('#' + evt.target.value + "_block").show();
}
}

Here is a solution done in jQuery. Remove the onclick from your html element.
$( document ).ready(function() {
$('#personal_family_type').on('click', function() {
$("#"+this.id + "_" + this.value + "_block").toggle();
});
});
Here is a Demo

You should definitely use jQuery in this case. If I understand your question correctly, you could do something like this:
$("#personal_family_type option:selected").click(function() {
var family_select_option = $(this).val();
$('#personal_family_type_'+family_select_option+'block').show();
});

Given:
<select size="1" id="personal_family_type" name="personal_family_type"
class="form-control btn btn-primary"
onchange="select_to_text('personal_family_type')">
You can instead do:
<select size="1" name="personal_family_type"
class="form-control btn btn-primary"
onchange="select_to_text(this)">
then in the function:
// a is a reference to the element calling the function
function select_to_text(a) {
var aa = a.value;
then I think you want:
if (aa !== "0") {
var el = document.getElementById(a.name + '_' + aa + '_block');
// set display to empty string so adopts default or inherited style
if (el) el.style.display = '';
}
}
which can be reduced to:
function select_to_text(a) {
if (aa.value !== '0')
document.getElementById(a.name + '_' + aa.value + '_block'.style.display = '';
}

Related

Sortable not changing ids

I want to be able, when I drag and drop, to replace all ids by the other.
For example in this code :
<div class="container">
<div class="row" id="row_0">
<div class="col-md-12">
<form id="form_0" onsubmit="return false;">
<select class="select2" name="test1" id="test1_0">
<option value="o_test">o_test1_1</option>
<option value="o_test">o_test1_2</option>
<option value="o_test">o_test1_3</option>
</select>
<select class="select2" name="test2" id="test2_0">
<option value="o_test">o_test2_1</option>
<option value="o_test">o_test2_2</option>
<option value="o_test">o_test2_3</option>
</select>
<button onclick="addRow()">clone</button>
</form>
</div>
</div>
<div class="row" id="row_1">
<div class="col-md-12">
<form id="form_1" onsubmit="return false;">
<select class="select2" name="test1" id="test1_1">
<option value="o_test">o_test1_1</option>
<option value="o_test">o_test1_2</option>
<option value="o_test">o_test1_3</option>
</select>
<select class="select2" name="test2" id="test2_1">
<option value="o_test">o_test2_1</option>
<option value="o_test">o_test2_2</option>
<option value="o_test">o_test2_3</option>
</select>
<button onclick="addRow()">clone</button>
</form>
</div>
</div>
</div>
I want to be able to change when I drag and drop all id="form_0" <-> id="form_1",id="row_0" <-> id="row_1", id="test1_0" <-> id="test1_1" .. etc, this is just an example, there are more.
I know that we can use the stop option like so :
$('.container').sortable({
stop: function(event, ui) {
var moved = ui.item,
replaced = ui.item.prev();
if (replaced.length == 0) {
replaced = ui.item.next();
}
var moved_num = parseInt(moved.attr("id").match(/\d+/g), 10) + 1;
var replaced_num = parseInt(replaced.attr("id").match(/\d+/g), 10) + 1;
moved.find('[id]').each(function() {
var $this = $(this),
split = $this.prop('id').split('_')[0];
$this.prop('id', $this.prop('id').split('_')[0] + '_' + replaced_num);
});
replaced.find('[id]').each(function() {
var $this = $(this),
split = $this.prop('id').split('_')[0];
$this.prop('id', $this.prop('id').split('_')[0] + '_' + moved_num);
});
}
});
The idea here in the code above, is to get the id number of the one moved and replaced, and for each id, replace in each one of them the number of the other.
But it doesn't do what I'm trying to do. Any idea why?
Fiddle : https://jsfiddle.net/763opz0c/
My suggestion is loop through all items and use their index within the container to update all id's
$('.container').sortable({
stop: function(event, ui) {
var $items = $(ui.item).parent().children()
$items.each(function(index){
$(this).find('[id]').add(this).attr('id', function(){
return this.id.split('_')[0] +'_' + index
});
});
}
});
Fiddle demo

Show/hide divs based on values selected in multiple select2 dropdowns

I am building a search result filtering feature. I have a number of select2 dropdown boxes where the user can select multiple values from to either hide or show divs with matching class values. I have a number of divs with classes containing values matching values in the select2 dropdown boxes. How do I go about coding this functionality?
I can only get this to work for one selection, I'd like to be able to select multiple options from the dropdowns.
$('select.filterCandidates').bind('change', function() {
$('select.filterCandidates').attr('disabled', 'disabled');
$('#candidates').find('.row').hide();
var critriaAttribute = '';
$('select.filterCandidates').each(function() {
if ($(this).val() != '0') {
critriaAttribute += '[data-' + $(this).data('attribute') + '*="' + $(this).val() + '"]';
}
});
$('#candidates').find('.row' + critriaAttribute).show();
$('#filterCount').html('Showing ' + $('div#candidates div.row:visible').length + ' Matches');
$('select.filterCandidates').removeAttr('disabled');
});
$('#reset-filters').on("click", function() {
$('#candidates').find('.row').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">
<br>
<h4>Search Form</h4>
<br>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="type" class="form-control filterCandidates" data-attribute="type">
<option value="0">Candidate Type</option>
<option value="CA">CA</option>
<option value="CFA">CFA</option>
<option value="CFO">CFO</option>
<option value="CIMA">CIMA</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="role" class="form-control filterCandidates" data-attribute="role">
<option value="0">Preferred Role</option>
<option value="Analyst">Analyst</option>
<option value="Associate">Associate</option>
<option value="CFO">CFO</option>
<option value="FD">FD</option>
<option value="FM">FM</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select id="roleType" class="form-control filterCandidates" data-attribute="roleType">
<option value="0">Preferred Role Type</option>
<option value="Permanent">Permanent</option>
<option value="Contract/Interim">Contract/Interim</option>
<option value="Internship">Internship</option>
</select>
</div>
</div>
</div>
just to give you a rough idea as you have not provided any code.
<script>
var SelectedValues = $('#ddlSelect option:selected');
var NotSelectedValues $('#ddlSelect option:not(:selected)');
$(SelectedValues ).each(function () {
$("."+$(this).val()+"").show(); //show all those divs containing
//this class
});
$(NotSelectedValues ).each(function () {
$("."+$(this).val()+"").hide();//hide all those divs containing
//this class
});
</script>
This is a rough idea , The above script will show all of the divs containing the classes you have selected in your select2 with id "ddlSelect" and hide those which you have not selected.
you can put this into a function and call it on onchange event of ddlSelect or whatever and however you want it to.

JavaScript: Remove HTML form input group

I'm having some issues getting the removeElement function to work as expected. I want the addElement function to add a new input group with a dropdown and a Remove button (which it does). The Remove button should call the removeElement function, removing the respective input group, which it does the first time but no more.
Here is the Code:
function addElement(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
var serviceID = 0; // reset number of services added
function addService() {
serviceID++; // increment for UID for new input
var html = `<div class="form-row"><div class="form-group col-6"><select name="service[]" class="form-control"><option value="basic">Basic Service</option><option value="full">Full Service</option><option value="tie">Ski Tie</option></select></div><div class="form-group col-3"><input type="button" class="btn btn-danger" onclick="javascript:removeElement('service' + serviceID + ''); return false;" value="Remove"></div></div>`;
addElement('services', 'div', 'service' + serviceID, html);
}
<div id="services">
<h4>Services</h4><br>
<div class="form-row">
<div class="form-group col-6">
<select name="service[]" class="form-control">
<option value="basic">Basic Service</option>
<option value="full">Full Service</option>
<option value="tie">Ski Tie</option>
</select>
</div>
</div><br>
There seems to be two issues in your code (based on what you have shared)
serviceID needs to be declared globally so that onclick handler can access the same.
No element is assigned the id as services
like
<h4 id="services">Services</h4><br>
Finally you need to invoke addService method as well.
Demo
var serviceID = 0;
function addElement(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addService() {
serviceID++; // increment for UID for new input
var html = `<div class="form-row"><div class="form-group col-6"><select name="service[]" class="form-control"><option value="basic">Basic Service</option><option value="full">Full Service</option><option value="tie">Ski Tie</option></select></div><div class="form-group col-3"><input type="button" class="btn btn-danger" onclick="javascript:removeElement('service' + serviceID + ''); return false;" value="Remove"></div></div>`;
addElement('services', 'div', 'service' + serviceID, html);
}
addService() ;
<h4 id="services">Services</h4><br>
<div class="form-row">
<div class="form-group col-6">
<select name="service[]" class="form-control">
<option value="basic">Basic Service</option>
<option value="full">Full Service</option>
<option value="tie">Ski Tie</option>
</select>
</div>
</div>

Get ID of all child elements and its input/select data

How can I get the id of each child element and its tag name so I can save the data of each column to a string?
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
I've got the loop so far, but I don't know how to get the data depending on the input/select:
for (var j = 0; j < (nCols / nRows); j++) {
}
You could use .find('*') to get all the childs :
$('.row').find('*').each(function(){
//Get the id and value
})
Hope this helps.
$('.row').find('*').each(function(){
if($(this).prop('tagName')!='OPTION')
console.log("id = "+$(this).prop('id')+" / value = "+$(this).val());
else
console.log("id = "+$(this).prop('id')+" / value = "+$(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='first input'>
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='second input'>
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2" selected>test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
If I understood you correctly you can get all input's values simply by iterating through them with jQuery:
$.each($('.col input, .col select'), function(index, item) {
console.log('ELEMENT ID ' + $(item).attr('id') + ' VAL - ' + $(item).val());
});
of simply use serializeArray method like this:
$('input, select').serializeArray()
Working example of both ways here: https://jsfiddle.net/hc882g27/
P.S.: in pure javascript it could be done with querySelectorAll function:
var items = document.querySelectorAll('.col input, .col select');
for (var i = 0; i < items.length; i++) {
console.log(items[i].value);
}

Fill select list with values depending on preselection

I want to have one select list populated with different values (price) depending on which option was chosen in other select list (sale or rent)
So what I have done is first create the arrays for sale and rent.
Then get the jquery and do an change event to pick which selection was made.
then a Switch statement that should populate the select list in question, but it is not showing anything. While jquery is a library for javascript I dont know if mixing them like I have done is alright:
$('#transaction').change(function(){
$value = $('#transaction').val();
var sale = [];
for (var i = 350000; i <= 2000000; i+100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i+100) {
rent.push(i);
}
switch($value) {
case 'sale':
$.each(sale, function(key, value){
$('#price').append('<option value="' + index+ '">' + value + '</option>')
break;
case 'rent':
break;
}); // end of each
} // end of switch
}) ; //end of jquery snippet
<div class="row">
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('transaction', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="select">Select</option>
<option value="sale">Sale</option>
<option value="rent">Rent</option>
<option value="holiday">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>
You dont have the options element in your select tag, so it never gets the $value from this statement :- $value = ('#transaction').val();
Insert the option tags and then run your example.
All credits go to Keith Wood (Sydney)
$(function() {
$('#transaction').change(function() {
var sale = [];
for (var i = 350000; i <= 2000000; i += 100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i += 100) {
rent.push(i);
}
var option = $('#transaction').val();
var prices = (option === '1' ? sale : (option === '2' ? rent : []));
var options = '';
$.each(prices, function(key, value) {
options += '<option value="' + value + '">' + value + '</option>';
});
$('#price').html(options);
});
});
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('street', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="0">Select</option>
<option value="1">Sale</option>
<option value="2">Rent</option>
<option value="3">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>

Categories

Resources