Change select to check boxes using javascript - javascript

The reason I would like to do this, is that it will be situational. If a user is logged in, they will see drop downs. If not, they will see a list of text. Ideally just plain text, but I don't know if that's possible, so I was thinking I could convert the <select> to checkboxes and hide the check boxes with CSS.
Basically we don't want a user who isn't logged in to feel they can select anything, because they won't be able to order and this could lead to frustration. But we would still like them to view what options are available for each product as unselectable text. If there is a better way to do this than what I'm thinking, I'd be grateful for suggestions. For now, this is what I've patched together, but it's not changing the select to checkboxes.
I grabbed some code from here to use as a starting point: http://www.w3schools.com/jsref/met_element_setattribute.asp
Also, I can't grab the < select > by id, because this will be on all < select >'s.
<select id="unique_id" class="unique_class" data-attribute_name="unique_attribute_name" name="unique_name">
<option value="" selected="selected">Choose an option</option>
<option class="attached enabled" value="516">5/16"</option>
<option class="attached enabled" value="38">3/8"</option>
</select>
Javascript:
function myFunction() {
document.getElementsByTagName("SELECT")[0].setAttribute("type", "checkbox");
}
Here is a fiddle: https://jsfiddle.net/d4qdekom/

This should convert your select to checkboxes, provided there is an HTML element with an id of "container" to append the new checkboxes.
This is the HTML
<select id="unique_id" class="unique_class" data-attribute_name="unique_attribute_name" name="unique_name">
<option value="" selected="selected">Choose an option</option>
<option class="attached enabled" value="516">5/16"</option>
<option class="attached enabled" value="38">3/8"</option>
</select>
<div id="container"></div>
The JavaScript function to transform the select to checkboxes below
function myFunction() {
var select = document.getElementById('unique_id');
var container = document.getElementById('container');
var i;
for (i = 0; i < select.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'option';
checkbox.id = 'randomId' + i;
checkbox.value = select.options[i].text;
var label = document.createElement('label')
label.htmlFor = 'randomId' + i;
label.appendChild(document.createTextNode(select.options[i].text));
container.appendChild(checkbox);
container.appendChild(label);
}
}
You can then go ahead and remove the select from the DOM. I guess all these should be made easier with JQuery
This is an update using getElementsByTagName:
var selects = x.getElementsByTagName('SELECT'); // this is a node list
for (var i = 0; i < y.length; i++) {
var select = selects[i]; // this is a single select element
// You can call the above function on each select here...
}
This is a working jsFiddle
I hope this helps.

If I am understanding your goal correctly, you can just put div's in and hide/show or enable/disable the div's depending on if the user is logged in or not. So wrap your select up in a div and just toggle that.
This would avoid trying to change the html by simply showing/hiding or enabling/disabling what you want the user to see.

Related

Select a drop-down value using javascript (Bookly WP Plugin)

I'm trying to select a drop-down value using js. In my case, I need to select "DRAW PORTRAIT" drop-down option after the plugin loads.
I tried two methods but I'm not getting anywhere. This is a part of the frontend found in Bookly WordPress plugin. I added an id id="category" to the dropdown so that I can select a value.
HTML:
<div class="bookly-js-chain-item bookly-table bookly-box" style="display: table;">
<div class="bookly-form-group">
<label>Service Type</label>
<div>
<select id="categorydraw" class="bookly-select-mobile bookly-js-select-category">
<option value="">Select category</option>
<option value="6">DRAW PORTRAIT</option>
<option value="7">DRAW DUMMY FIGURE</option>
<option value="8">DESIGN WAX SCULPTURE</option></select>
</div>
</div>
</div>
Method 01
document.getElementById("categorydraw").value = "DRAW PORTRAIT";
Method 02
var objSelect = document.getElementById("categorydraw");
setSelectedValue(objSelect, "DRAW PORTRAIT");
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
Please see the full code where the js doesn't work: https://jsfiddle.net/3z5hcv62/
I would really appreciate if someone can correct my cranky code. Thanks in advance!
One line of jQuery will allow you to select the item necessary:
$('#categorydraw option[value="7"').prop("selected", true);
https://jsfiddle.net/fLc1p5mq/
Edit: In order to activate on a WordPress page load, use:
jQuery( document ).ready(function() {
jQuery('#categorydraw option[value="7"').prop("selected", true);
});
First, i want to make sure. Do you want to select the value of the dropdown or set the value to the dropdown?. Maybe this will help your problem.
HTML
<!-- I set the "categories" id to the dropdown -->
<select class="bookly-select-mobile bookly-js-select-category" id="categories">
<option value="">Select category</option>
<option value="1">Cosmetic Dentistry</option>
<option value="2">Invisalign</option>
<option value="3">Orthodontics</option>
<option value="4">Dentures</option>
</select>
<p>
Selected value: <strong id="selected"></strong>
</p>
JavaScript
var dropdown = document.getElementById('categories');
var datas = [];
var select = 3;
/* Get value with text from dropdown */
for(var i=0;i<dropdown.options.length;i++) {
datas.push({
id: dropdown.options[i].value,
text: dropdown.options[i].text,
});
}
/* For set the value */
dropdown.value = select; // after page loaded,, default value will selected is "Orthodontics"
/* For select current value with the text */
var dataSelected = datas[select];
document.getElementById('selected').innerHTML = "ID: "+dataSelected.id+", TEXT: "+dataSelected.text;
The result will show like this https://jsfiddle.net/65jnzLko/1/
You can improve that code. Like selecting datas by id of the dropdown value.
Or if you just want to set the value for your dropdown, you can do this
// using pure js
document.getElementById('yourdropdown').value = 3 // or other values
// using jquery
$("#yourdropdown").val(5) // 5 can replace with other values

select drop down option based on associated text

I have a drop down with a value and associated text as such:
echo '<option value="'.$row['company_id'].'">'.$row['company_name'].'</option>';
Eventually, the output of the selected option is put into a table, row by row. By each row, there is an edit button to edit that particular row and select a new drop down option. I'm trying to use JavaScript to select the text and when they hit the edit button, the option that is currently set will be the default choice.
So for instance, if the row says the company_name is: ABC Company, when they hit the edit button, the drop down will populate with that option. Since the value and text are different, I need to choose the drop down option based on text. I have tried these 2 options so far with no luck.
To get the row text:
var d = document.getElementById("itable").rows[id].cells[3].innerText;
I have tried the following to pass back the text of the row, and to select the drop down by text.
document.querySelector('#editinsurancepolicymodal select[name=editicompanydropdown]').value = d;
This option just populates the drop down, but no choice is selected.
document.querySelector('#editinsurancepolicymodal').find('option[text="InsuranceB"]').val;
This option selects the first option in the drop down, but doesn't change based on what the 'text' is.
Thank you for your help in advance.
One way will be to iterate over the option elements, selecting the one that has the same text as the text from the row, and un-selecting all the others. This is illustrated in the snippet below (I have inserted a 3 second timeout, so that you can see that the initially selected option (Two) is changed to the option with the text "Three" from the JavaScript code.
window.setTimeout(function () {
var sampleWord = "Three";
var options = document.querySelectorAll("option");
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === sampleWord) {
option.selected = true;
} else {
option.selected = false;
}
}
}, 3000);
<select id="selector">
<option id="option-1" value="1">One</option>
<option id="option-2" value="2" selected>Two</option>
<option id="option-3" value="3">Three</option>
<option id="option-4" value="4">Four</option>
</select>
Alternately, you could store the id for the company as a data-attr attribute on the row. For example (in PHP):
echo "<td data-attr-company-id=".$row['company_id'].">".$row['company_name']."</td>"
Then, you can read the attribute from the table row, and query for the option that has the same value as your attribute value.
var options = document.querySelectorAll("option");
This will select all options from the page. If you want to get the options for a specific drop down, use the following:
var options = document.querySelector('#specificform select[name=specific_drop_down_in_the_specific_form]');
To select the option based on the text and not the value, use this loop:
for (var i=0; i<options.length; i++){
var option = options[i];
if (option.innerText === d){
option.selected = true;
}
}

HTML/Javascript Set up Two Select Options and redirect once first one is selected

<select id="First DropDown" name="" onchange="javascript:location.href = this.value;">
<option value="/url">Option1</option>
<option value="/url">Option2</option>
<option value="/url">Option3</option>
<option value="/url>Option4</option>
<option value="" selected="selected">Option5</option>'
</select>
<select id="Second DropDown" name="" onchange="javascript:location.href = this.value;">
<option value="/url">Option1</option>
<option value="/url">Option2</option>
<option value="/url">Option3</option>
<option value="/url>Option4</option>
<option value="" selected="selected">Option5</option>'
</select>
That's really all I got. Basically what I want is when someone selects an option (such as option 1) on the first dropdown menu, it then pulls up a specific set of options. So for example, if someone selects "Option 1" on the first drop down menu, then on the second drop down menu options such as "#1" "#2" "3" come up, but if someone selections "Option 2" on the first drop down menu, menu options such as "4" "5" "6" come up. I would also like to know how to set up a search button so that when both the drop downs have a specific set of option selected, it then redirects to a specific page I set. Sorry about all of this.. I know Im not very good
You need to create an event handler on the first text box that fills the second text box with options. A good way to do this is to store your options in a 2D array, so when the first select box is selected, your Javascript code can easily loop over and create the new options.
With HTML like this
<!-- In your own code, do not use onsubmit="return false" -->
<form id="searchForm" action="#" onsubmit="return false">
<input type="text" name="search" value="Search a little"/>
<fieldset>
<label>Search parameters</label>
<select id="first" name="first"></select>
<select id="second" name="second">
<option>-----</option>
</select>
</fieldset>
<input type="submit" value="Search" />
</form>
and Javascript like this:
var options = [
["A","B","C"],
["D","E","F"],
["G","H","I"],
["J","K","L"]
],
first = document.getElementById('first'),
second = document.getElementById('second'),
searchForm = document.getElementById('searchForm'),
searchButton = document.querySelector('input[type="submit"]'),
destination,
option;
// Fill the second text box with options from the array.
function fillSecond() {
// Get the list of options
var secondOptions = options[first.value];
// Clear the previous options
second.innerHTML = '';
// Add each option to the select box
for (var i = 0; i < options[first.value].length; i++) {
option = document.createElement('option');
option.value = secondOptions[i];
option.innerHTML = 'Option ' + secondOptions[i];
second.appendChild(option);
}
// Select the first option by default.
second.firstElementChild.setAttribute('selected','selected');
// update the from
updateFormAction();
};
function updateFormAction() {
searchForm.action = destination = '#' + first.value + second.value;
}
// When the second box is updated, update the second select
// and update the form action
first.addEventListener('change', fillSecond);
// Fill the first select box with options
for (var i = 0; i < options.length; i++) {
option = document.createElement('option');
option.value = i;
option.innerHTML = 'Option ' + i;
first.appendChild(option);
}
// By default select the first element.
first.firstElementChild.setAttribute('selected','selected');
// When search is clicked, alert where the form will take them
searchButton.addEventListener('click', function () {
alert('Sending user to location: ' + destination);
return false;
});
// When the second box is updated, update the form action
second.addEventListener('change', function () {
updateFormAction();
});
// On startup, fill the second box.
fillSecond();
You can change where your form goes to based on which options the user selects from the drop down.
See the demo at this jsFiddle to get yourself started
What you are looking for is called "Chained Select Box" - you can change the options values easy with Jquery, but better you take one Plugin which provides this functionality:
For Example:
http://www.appelsiini.net/projects/chained/demo.html
Or here if you are using a Database (MySQL) and PHP to provide the Content of your Select Boxes
http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/

How to populate a form list with buttons using javascript

I made a script that, when you press one button(accessories) the selection(mylist) populates with one array(accessoryData), and when you hit the other button(weapons) the other array(weaponData) populates the selection. However, in the current state of the code the second button press is not re-populating the selection. What is wrong here?
Also if there is a more efficient way to do this, that might be helpful.
Full code
function runList(form, test) {
var html = "";
var x;
dataType(test);
while (x < dataType.length) {
html += "<option>" + dataType[x];
x++;
}
document.getElementById("mylist").innerHTML = html;
}
I believe you are trying to make a <select> element ie the drop down menu, but proper markup is:
<select id="myList">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="n">Option n</option>
</select>
You forgot to close the <option> tag with innerHTML property.
Using native JS methods:
//create the select element
var select = document.create('select');
//or use getElementById if it's already there
//Assuming your datatype is an Array of string
var opt;
for(var i=0; i<datatype.length; i++){
//create the option element
opt = document.create('option');
opt.textContent = datatype[i]; //innerText works too
//set the value attribute
opt.setAttribute('value',i+1); //+1 or else it would start from 0
//add the option to the select element
select.appendChild(opt);
//conversely use removeChild to remove
}
//at last add it to the DOM if you didn't fetch it from the DOM.

How would I dynamically create input boxes on the fly?

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>

Categories