JS add attribute to string - javascript

I have a post ajax that return retorno1 and just to get it simple i put their output as string value as ajax posted like the example .. then I need to add more than 1 option that the value is 0 so I need to say if the value is 0 show the selected item "NON" and if the value other so show it and select it.
I'm using setAttribute("selected", "selected") but I know it's wrong, so what is the correct code to add attribute to this string?
var i = 0;
var returno1 = "<option value='21'>Hello</option><option value='22'>Bye</option>";
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(pre)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();
$.each($.parseHTML(pre),function(i,item){
var val_drop =($(item).val());
var text_drop =($(item).html());
if (val_drop == dep_dr){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}else if(dep_dr == "0"){
jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
}
})

Working fiddle
Try to use attr() or prop() to set or get attribute to elements, check example bellow :
jQuery("#departamento_drop").empty();
$.each($.parseHTML(pre),function(i,item){
var current_itme=$(item);
var val_drop =current_itme.val();
var text_drop =current_itme.html();
if (val_drop == dep_dr || dep_dr == "0"){
current_itme=current_itme.attr("selected", "selected");
}
jQuery("#departamento_drop").append(current_itme);
})
Hope this helps.

Why do you need use strings? Use objects insted.
var values = [{val:33, title:'Hi'},{val:34, title:'Bue'},{val:0, title:'-------NA-------'}],
selected = 34;
values.forEach(function(item){
$('#dd').append($('<option>', {value:item.val, text:item.title, selected: item.val==selected}));
})

Related

Get current option in multiselect

How to get the current selected/unselected in a Jquery multiselect?
I already know how to get the selected values in a multiselect. The problem is that I need to get the one that was currently selected/unselected when the user clicked on it. It looks like a trivial question but I haven't really found a proper solution so far.
This is what I previously tried:
$('#mySelect').change(function(){
var element = $(this).val();
})
Unfortunately it returns an array with all selected options. What I need is to get the current either selected or unselected value by the user. I just tried to create a method myself using auxiliar variables and it seems that it works now.
if($(this).attr('id').includes('Type')) Key = "trackertype";
if(selectedValue.length > 0 && $(this).val() == null){
Value = selectedValue[0].toString();
selectedValue = [];
Key = '-' + Key;
}else if(selectedValue.length == 0 && $(this).val() != null){
selectedValue.push($(this).val()[0]);
Value = selectedValue[0].toString();
}else if(selectedValue.length > 0 && $(this).val() != null && selectedValue.length < $(this).val().length){
var selected = true;
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = current.toString();
selectedValue.push(current.toString());
selected = false;
}
});
});
}else if(selectedValue.length > $(this).val().length){
$.each($(this).val(),function(i,item){
var current = item.toString();
$.each(selectedValue,function(i,itemV){
if(current != itemV.toString()){
Value = itemV.toString();
selectedValue = jQuery.grep(selectedValue, function(value) {
return value != itemV.toString();
});
selected = true;
}
});
});
}
if(selected){
Key = '-' + Key;
}
I needed to send Value(value of the current selected option) and Key(select Name) to a web service. Its not the best possible code(sorry about that) but it actually does its job.
Thanks
var selectedItems = document.querySelectorAll('#selectBoxid option:checked');
// here selectboxid is id of select element of your page.
It is simple when any html element can get using document.getElementsById('id').
Just same as if you want to get html element using css class or any css selector rather than id of element or name of html element.
For example :
<p class="text-center" > abcd </p>
Then, we can retrive all html using:
document.querySelectorAll('.text-center')
Same in given example we want option html element which is selected for that property I use:
document.querySelectorAll('option:checked');

How can I get a specific variable reading the data atribute on element?

I have some fields on my site, and they are the same, but each one of then should update some jquery variable with it's value.
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
I need that depending on the data-atribute, they run the same function, but update the variable pointed in the atribute.
Example:
for = "0";
int = "0";
agi = "0";
$( "input" ).focusout(function() {
data-atribute-of-the-element = $(this).val;
})
I have no know idea how to do this.
And seems stupid to create a different function for every input.
Thanks in advance!
Create an object which has a field which is your variable. Something like below.
var a={'for':'0','int':'0','agi':'0'}
$( "input" ).focusout(function() {
a[$(this).attr('data-atribute')] = $(this).val();
console.log(a.for);
console.log(a.int);
console.log(a.agi);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
.attr() does work, but since you're using data attributes anyway, you may as well use the .data() function designed for them.
See comments in the code snippet for explanation:
/* Set up an object to contain the values you're capturing.
This means we won't have to predefine all the variables or
set them individually; it also means you can use reserved words
like "for", which wouldn't work as variables on their own: */
var capturedValues = {};
$( "input" ).focusout(function() {
// This gets the contents of the "data-atribute" attribute:
var theName = $(this).data("atribute");
// This captures the value of the current input field,
// and puts it in the capturedValues object using theName as the key:
capturedValues[theName] = $(this).val();
// Later on you can reference these as e.g. capturedValues.agi
// Show the results (just for demo):
console.log(capturedValues);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
How about:
var for = "0";
var int = "0";
var agi = "0";
$( "input" ).focusout(function(s) {
switch ($(this).attr('data-attribute')) {
case 'for':
for = $(this).val();
break;
case 'int':
int = $(this).val();
break;
case 'agi':
agi = $(this).val();
break;
}
//OR
var t = $(this).attr('data-attribute');
if (t == 'for') for = $(this).val();
else if (t == 'int') int = $(this).val();
else if (t == 'agi') agi = $(this).val();
})
PS: 'atribute' has 2 t's : attribute
Use the .attr function of jQuery:
$( "input" ).focusout(function() {
let data-atribute-of-the-element = $(this).attr('data-atribute');
})

Can i call another function inside the GetElement in Javascript

I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">

.clone doesn't not appear to be incrementing

this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>
For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.
I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});

Get all div values of similiar id in a particular div

I have a div structure like below
<div id=main">
<input type="hidden" id="people_0_1_0" value="12"/>
<input type="hidden" id="people_0_1_1" value="12"/>
</div>
Now how to add all hidden input values in a variable. Thanks
Using Jquery's map function
var myArray = $('#main input').map(function(){
return $(this).val();
}).get();
It will collect all input's values(12 and 12 in this case) to array variable.
See jsfiddle http://jsfiddle.net/GkXUS/1/
If you want to get sum of values you can do the following
var total = 0;
$.each(myArray,function() {
total += parseInt(this,10);
});
​
var total = 0;
$('#main input[id^="people_"]').each(function(){
total += parseInt(this.value, 10);
});
Note that I am using attribute starts with selector to find all the input elements whose id starts with people_.
total will give you the total of all the input elements value.
I guess you want this:
var hidden_value = new Array();
var hiddens = document.getElementById( "main" ).childNodes;
for( i = 0 ; i < hiddens.length ; i++ ){
hidden_value.push( hiddens[ i ].value );
}
You could try something like this:
var peopleData = $("#main input[type=hidden]").serializeArray();
Putting values in a variable does not make sense. You can insert the values in a Array and perform your required operation
Using Plain Javascript
var els=document.getElementById('main').childNodes;
var a​llVal​=​​​​​​​​[];
for(i=0; i<els.length-1; i++)
{
if(els[i].nodeType != 3 && els[i].type=="hidden") allVal.push(els[i].value);
}
console.log(allVal); // the array
console.log(allVal[0]); // first value
An example is here.

Categories

Resources