Need to Get the rid of many if's - javascript

I have variable in my java script which is global. Now i got different value each time when inner function call. I need to create a option tags with selected value as in attribute and one for without selected value based on the variable. I guess this is more confusing let me give you a example.
var a1 = "a1c" // default value but may change
if(a1 == "all")
{
var allstatusdefault = '<option value="all" selected="selected">All</option>';
}
else
{
var allstatusdefault = '<option value="all" >All</option>';
}
if(a1 == "a1b")
{
var allstatusdefault1 = '<option value="a1b" selected="selected">a1b</option>';
}
else
{
var allstatusdefault1 = '<option value="a1b" >a1b</option>';
}
if(a1 == "a1bc")
{
var allstatusdefault2 = '<option value="a1bc" selected="selected">a1bc</option>';
}
else
{
var allstatusdefault2 = '<option value="a1bc" >a1bc</option>';
}
This is just sample but i have to generate lot of option tag with different values.I don't want to write to many if ..anybody have any other idea?

Extract common code, I see a lot of duplication here.
var a1 = "a1c";
function buildOption(id) {
var selected = (a1 == id? ' selected="selected"' : '');
return '<option value="' + id + '"' + selected + '>' + id + '</option>';
}
var allstatusdefault = buildOption('all');
var allstatusdefault1 = buildOption('a1b');
var allstatusdefault2 = buildOption('a1bc');

From what i can deduct here is what you should do
var default1 = '<option value="'+a1+'" selected="selected">'+a1+'</option>';
var default2 = '<option value="'+a2+'" selected="selected">'+a2+'</option>';
Since the value of a1 is reused in the string, might as well just set it right away instead of using multiple if statements.
Note: when you have many if statement its the perfect opportunity to use a switch statement

For starters, learn about switch...case. In your case, it looks like you could possibly simply use the variable itself in the formation of the strings by concatenating the variable to a string.

var a1 = "a1bc" // default value but may change
switch(a1)
{
case "all" : allstatusdefault = '<option value="all" selected="selected">All</option>';break;
case "a1b" : allstatusdefault = '<option value="a1b" selected="selected">a1b</option>'; break;
case "a1bc" : allstatusdefault = '<option value="a1bc" selected="selected">a1bc</option>'; break;
default : allstatusdefault = '<option value="all" >All</option>';break;
}
window.alert(allstatusdefault); ​

I think from the way you are writing code you could do one with use jQuery. Create entire HTML first, with all the option values using jQuery object like this :
var $optionHTML = $('<option value=""> Blahblah </option>');
Now you can apply all jquery function to this guy. so you append a new option like this.
$optionHTML.append('<option>...</option>')
when you are done with all the option element use jquery selector method to find an element with option having value attribute matching to a1c then add attribute selected then you are done.
Do let me know if you need some code for starters.
Thanks.
EDIT :
HERE IS THE ANSWER
<html>
<head>
<script type = "text/javascript" src= "http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type = "text/javascript">
$(document).ready (function () {
var value = "test 2";
$select = $("<select></select>");
$optionHTML1 = $('<option value="test 1">Test 1</option>');
$optionHTML2 = $('<option value="test 2">Test 2</option>');
$optionHTML1.appendTo($select);
$optionHTML2.appendTo($select);
$select.find("[value='test 2']").attr('selected','selected');
alert($select.html());
$("div").append($select);
});
</script>
<style type = "text/css">
</style>
</head>
<body>
<div>
</div>
</body>

Related

How to programmatically select an option inside a variable using jQuery

Let say I have this variable html which contain these select options:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
How can I programmatically select an option which is inside the html variable so when I append them to somewhere, for example
$(this).children('div').append(html);
it will become like this:
<div> <!-- children div of the current scope -->
<select>
<option value="10" selected>10</option>
<option value="20">20</option>
</select>
</div>
How is it possible?
edit: the variable contents is generated from remote locations, and I must change the value locally before it is being appended into a div. Hence, the question.
edit 2: sorry for the confusion, question has been updated with my real situation.
You can cast the HTML into a jQuery element and select the value at index 0. Then you can add it to the DOM.
Here is a simple jQuery plugin to select an option by index.
(function($) {
$.fn.selectOptionByIndex = function(index) {
this.find('option:eq(' + index + ')').prop('selected', true);
return this;
};
$.fn.selectOptionByValue = function(value) {
return this.val(value);
};
$.fn.selectOptionByText = function(text) {
this.find('option').each(function() {
$(this).attr('selected', $(this).text() == text);
});
return this;
};
})(jQuery);
var $html = $([
'<select>',
'<option value="10">10</option>',
'<option value="20">20</option>',
'</select>'
].join(''));
$('#select-handle').append($html.selectOptionByIndex(0));
// or
$html.selectOptionByValue(10);
// or
$html.selectOptionByText('10');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-handle"></div>
By default, the first option will be selected - if you want to do on any other set it so using the index as soon as the select is appended:
$('#select_handle option:eq(1)').prop('selected', true)
(this selects the second option)
See demo below:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
$('#select_handle').append(html);
$('#select_handle option:eq(1)').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select_handle"></div>
You could try simply setting the value of the drop-down to the one you wish to 'select' - like
$("#select_handle select").val( a_value );
For example, if a_value is 30 it will add the needed HTML to the DOM node. This would be my take:
$(function() {
var html = '<select>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select>';
// set a value; must match a 'value' from the select or it will be ignored
var a_value = 30;
// append select HTML
$('#select_handle').append(html);
// set a value; must match a 'value' from the select or it will be ignored
$("#select_handle select").val(a_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>select added below</h2>
<div id="select_handle">
</div>
selected="selected" will work
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20" selected="selected">20</option>'+
'</select>';
$('#select_handle').append(html);
You can do this in jQuery using the .attr() function and nth pseudo-selector.
Like so:
$("option:nth-child(1)").attr("selected", "");
Hope it helps! :-)
after the append, try $('#select_handle select').val("10"); or 20 or whatever value you want to select

Create element select-option and selected value

I am trying the code given below :
var tmp1 = "3";
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'>Proses</option><option value='1'>Return</option><option value='2' >Selesai</option></select>";
$('select.status_detail_hanca').val(tmp1);
$(".tbody_detail_hanca_checking").append(status_detail_hanca);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tbody_detail_hanca_checking'>
</div>
but this code is not working, tmp1 value from json and this select-option in loop $.each.I am trying this code also :
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'"+ if(tmp1 === '0'){$(this).append("selected")} +">Proses</option><option value='1'"+ if(tmp1 === '0'){$(this).append("selected")} +">Return</option><option value='2'"+ if(tmp1 === '0'){$(this).append("selected")} +">Selesai</option></select>";
but, its also not working.
How to solve this problem ?
Thanks guys !
You can try something like this. Also Its better to use loop and create a string than hard-coding it
var tmp1 = "3";
var optionList = ["Proses", "Return","Selesai", "TEST", "FOO"]
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' >";
status_detail_hanca = optionList.reduce(function(p, c, i){
var _t = "<option value='"+i+"' ";
if(tmp1 == i){
_t += "selected='selected'";
}
_t += ">" + c + "</option>";
p += _t;
return p;
}, status_detail_hanca);
status_detail_hanca += "</select>";
$(".tbody_detail_hanca_checking").append(status_detail_hanca);
$(document).on("change", ".status_detail_hanca", function(){
console.log($(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tbody_detail_hanca_checking'>
</div>
You can use .prepend(), jQuery() to prepend an <option> element to select.status_detail_hanca with value and text set to tmp1, and selected property set to true.
var tmp1 = "3";
var status_detail_hanca = `
<select class='status_detail_hanca' name='status_detail_hanca[]'>
<option value='0'>Proses</option>
<option value='1'>Return</option>
<option value='2' >Selesai</option>
</select>`;
$(".tbody_detail_hanca_checking")
.append(status_detail_hanca);
var select = $("select.status_detail_hanca")
.prepend($("<option>", {value:tmp1, selected:true, text: tmp1}));
console.log(select.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class='tbody_detail_hanca_checking'>
</div>
//Selection on base of select option text
$(".status_detail_hanca option:contains("+ $.trim("Text you want to select") +")").attr('selected', 'selected');
//Selection on base of select option value
$('.status_detail_hanca').val(name);
add dot before class name from selecting element by class i.e $('.ClassName').opertion();

javascript get all inputs inside div including select and textarea

I have been trying to figure out how to get all the input elements inside a div including select and textarea and pass them to editor, so far i figured out with input but i am just stuck with the rest.
Here is the code so far
function InsertShortcode(elem) {
var shortcodeName = elem.parentElement.id;
var inputs = document.getElementById(shortcodeName).getElementsByTagName('input'), i=0, e;
var inputs_val = '[' + shortcodeName;
while(e=inputs[i++]){
if(e.id){
inputs_val += ' ' + e.id + '="' + e.value + '"';
}
}
inputs_val += ']';
window.send_to_editor(inputs_val);
}
By this i am able to grab all the inputs inside a div where submit button is but still i am not sure how to grab textarea or select inputs.
The problem is that i have to make it dynamic. I will have many "shortcodes" and each will be in it's own div where the button is. But each will have it's own inputs which i can't control so i need to grab them all and send values to editor. Here's example of the code.
<div class="output-shortcodes">
<?php foreach( $theme_shortcodes as $key => $name ) { ?>
<div id="<?php echo $key ?>">
<p>
<h2><?php echo $name ?></h2>
</p>
<?php $form = $key . '_form';
if(function_exists($form)) {
$form(); // this is where the input fields are dynamically created on each shortcode.
}
?>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<?php } ?>
</div>
Use jQuery and the :input pseudo selector:
$('.output-shortcodes').find(':input');
That simple.
https://api.jquery.com/input-selector/
Or wrap it in a <form>, then you can use:
document.getElementById("outputForm").elements...
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
You can target your wrapper element and locate thru .find() all inputs within:
var inputs = $("#" + shortcodeName).find("select, textarea, input");
If you can use jQuery here is a fiddle: https://jsfiddle.net/q33hg0ar/
<div id="form">
<input type="text" name="input1" />
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<textarea name="notes"></textarea>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<script>
$(document).ready(function() {
$('#form').find('input, select, textarea').each(function() {
console.log($(this).attr('name'));
});
});
</script>
And here it is w/o jQuery: https://jsfiddle.net/67pp3ggu/
window.onload = runIt();
function runIt() {
var elements = document.getElementById('form').childNodes;
var inputTypes = ['text', 'select-one', 'textarea'];
for (var i = 0; i < elements.length; i++) {
var elm = elements[i];
if (typeof elm.type !== 'undefined' && inputTypes.indexOf(elm.type)) {
console.log(elm);
console.log(elm.type);
}
}
}
At the end i switched to jQuery code completely and using :input helped me to resolve the problem.
Here is the complete code that i use now.
$('.vivid-framework-submit-shortcode').click(function(event) {
event.preventDefault();
var shortcodeName = $(this).closest('div').attr('id');
var inputs = $('#' + shortcodeName).find(':input');
var inputsVal = '[' + shortcodeName;
inputs.each(function() {
if($(this).attr('id') != 'content') {
inputsVal += ' ' + $(this).attr('id') + '="' + $(this).val() + '"';
console.log(inputsVal);
}
});
inputs.each(function() {
if($(this).attr('id') == 'content' ) {
inputsVal += ']' + $(this).val() + '[/' + shortcodeName;
}
});
inputsVal += ']';
window.send_to_editor(inputsVal);
});
What does it do? So now when i click on a button within shortcode div first using preventDefault to prevent page to scroll to top, next i grab the id of that div using it as shortcode name, and lastly i grab all the inputs and check if one of the inputs have id content because that will decide if shortcode is enclosed or selfclosed and loop through all inputs outputting their id's and values. and at the end return that to the editor.
Some of the terms may be unfamiliar but those who are familiar to WordPress will recognize terms like shortcode...
At the end final output is:
[bartag foo="value" bar="value"]content from textarea[/bartag]
If you downvote my questions or answers please explain why because i always tend to explain or ask as detailed as i can.

fill the input type hidden from selected multiple option on jquery

I have a input that have type like this:
<input class="emailSend" name="emailSend" type="hidden">
Then I have a multiple select option like this
<div class="controls">
<select id="email" multiple data-rel="chosen" class="input-xlarge" name="email[]">
<?php
foreach ($atasan as $data) {
echo "<option value='" . $data['email'] . "'>" . $data['email'] . "</option>";
}
?>
</select>
</div>
My problem is, I want to fill that hidden input from the option that selected from multiple select option. So let say, the selected option is 'email1', 'email2', 'email3' then would be affected to hidden type like this 'email1, email2, email3'.
I have try this for 3 hour in jquery and I am stuck. My code is like this.
$("#email").change(function() {
var elements = $("#email option:selected").length;
var input = $(".emailSend");
$(".emailSend").html("");
$.each($("#email option:selected"), function(/*index, element*/) {
input.val(input.val() + $(this).html() + ", ");
if (index < elements - 1) {
//code to remove last comma
//any idea ?
}
});
});
So appreciated for the help...
EDIT Here is the fiddle :JSFIDDLE
Updated FIDDLE now that I see what you meant by looking at the fiddle you made.
this is actually all you need to do...
Updated to include spaces between the addresses!
$("#email").on('change', function() {
var thisval = $(this).val() + '';
var myarr = thisval.split(',');
var newval = '';
myarr.forEach(function(i,v) {
newval += i + ' , ';
});
newval = newval.slice(0, newval.length - 3);
$("#emailsend").val(newval);
});
Commented Version (for learning and stuff)
$("#email").on('change', function() {
//the extra space at the end is to typecast to string
var thisval = $(this).val() + '';
//takes string of comma separated values and puts them
//into an array
var myarr = thisval.split(',');
//Initialize a new string variable and loop through
//the array we just created with MDN's forEach()
var newval = '';
myarr.forEach(function(i,v) {
//add to the string through each iteration,
//including comma with spaces
newval += i + ' , ';
});
//use .slice() to trim three characters off the
//end of the final string. (strip final comma)
newval = newval.slice(0, newval.length - 3);
//and last but not least, assign our newly created
//and properly formatted string to our input element.
$("#emailsend").val(newval);
});

How to style dynamically generated Select2 dropdowns after the page has loaded?

I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.

Categories

Resources