javascript equivalent of jquery code - javascript

Can someone help what's the javascript equivalent of below jquery line.
$("#abc option[value='1']").text();
abc is the id of selectbox

var options = document.getElementById("abc").options;
for (var i = 0, j = options.length; i < j; i++) {
if (options[i].value == "1") {
alert(options[i].text);
}
}
The value and text attributes are available on the HTMLOptionElement per DOM Level 2.
(demo)
UPDATE
Updated demo with combined text, cf. comments:
var options = document.getElementById("abc").options,
text = "";
for (var i = 0, j = options.length; i < j; i++) {
if (options[i].value == "1") {
text += options[i].text;
}
}

This would be 100% equivalent to the selector:
var options = document.getElementById('abc').getElementsByTagName('option'),
text = "";
for(var i = 0, l = options.length; i < l; i++) {
var option = options[i];
if(option.value === '1') {
text += option.text;
}
}
Or if querySelectorAll is available:
var options = document.querySelectorAll('#abc option[value="1"]'),
text = "";
for(var i = 0, l = options.length; i < l; i++) {
text += options[i].text;
}
That said, you can make improvements depending on the HTML structure (e.g. if #abc is the select element etc).

In modern browsers it can be:
var option = document.querySelector('#abc option[value="1"]').textContent

The statement doesn't make sense. It gets the text from an option, and then just throws it away. I assume that you want to do something with the text, like assigning it to a variable.
// A variable for the result
var text = null;
// Get the options from the select element
var options = document.getElementById('abc').options;
// Find the option with the value "1"
for (var i = 0; i < options.length; i++) {
if (options[i].value == '1') {
// Get the text from the option
text = options[i].text;
// Exit from the loop
break;
}
}
Note: The original code would get the text from all options with the specified value, but this code only gets the text from the first option found. Having more than one option with the same value is pretty useless, so that feature of the original code is most likely unintended.

This Will Work.
document.querySelector(".producer option[value='1']").text;

Related

Returning XML node values

I need to return all XML values from a URL.
I have previously used the URL and it works fine.
This is what I have so far:
function displayXML(xml) {
var devices = xml.getElementsByTagName("device");
for (var i = 0; i < devices.length; i++) {
var deviceDetails = devices[i].children;
for (j = 0; j < deviceDetails.length; j++) {
console.log(devices[i].childNodes[j].nodeValue);
}
}
}
It manages to return the right amount of values: 33 tags 33 values
but it's returning null for each one. However, the XML file contains values for each tag.
Thanks
Based on an answer to this question
The nodeValue property of XML elements is always null. The value of the element is actually stored within text nodes inside the element so you will need to go down one more child to get it. Try this
var devices = xml.getElementsByTagName("device")[i].firstChild.nodeValue;
I think your script should look something like this with firstChild inserted when trying to get the value:
function displayXML(xml) {
var devices = xml.getElementsByTagName("device");
for (var i = 0; i < devices.length; i++) {
var deviceDetails = devices[i].children;
for (j = 0; j < deviceDetails.length; j++) {
console.log(devices[i].childNodes[j].firstChild.nodeValue);
}
}
}

Find select option value by text

I have the text of a select and need to find the option corresponding value.
I need to go because the select the item you seek is not selected
for (var i = 0; i < combo.length; i = i + 1) {
if (combo.options.text == text){ // if the text value of the combo equals my variable
var pref = combo.options[combo.selectedIndex].value;
alert(pref);
}
}
Need to compare the option in index i
for (var i = 0; i < combo.options.length; i++) {
if (combo.options[i].text == text) {
var pref = combo.options[i].value;
alert(pref);
}
}
Demo: Fiddle

jquery search for a table cell -> update neighboring cell

How do I go about finding a table cell with value (text) of "foo" and setting the next cell in that row to "bar"?
The cell to be set may already contain some text that needs to be overwritten.
Try this but i haven`t tested it.
$('td').filter(function(){
return $(this).text() === 'foo'
}).next('td').text('bar')
Demo
var rowList = document.getElementById('tableID').children;
for (var i=0, len = rowList.length; i < len; ++i) {
var row = rowList[i];
var cellList = row.children;
for (var j=0, size = cellList.length; j < size; ++j) {
var cell = cellList[j];
//need additional check to avoid out of bounds issues
if (cell.innerHTML == 'foo' && cellList[j + 1]) {
cellList[j + 1].innerHTML = 'bar';
}
}
}
EDIT
sorry missed the jQuery tag. The answer above is fine but I believe the calls to .text() should be .html()

Looping through and updating the values in a select list

I'm trying to update the options of ALL select lists on a page and implemented a solution found on Get list of all `input` objects using JavaScript, without accessing a `form` object and other pages.
This works to an extent but only the select lists which occur AFTER the one which is triggering the javascript are updated whereas I need them ALL done, regardless of their position relative to the triggering select.
Here's a simplified version of what I have:
function chooseBon(id, value) {
var bonbonsAmount = 12;
var bonbonsCurrent = 0;
var bonbonsCount = 4;
var inputs, index;
// get all the select lists
inputs = document.getElementsByTagName('select');
// loop through all the lists
for (index = 0; index < inputs.length; ++index) {
// First disable all options
for (j = 0; j<=bonbonsAmount; ++j) {
inputs[index].options[j].disabled="disabled";
}
// Then re-enable the ones we still need
for (j = 0; j<=(bonbonsAmount - bonbonsCurrent); ++j) {
inputs[index].options[j].disabled="";
}
// add up the no of chocs selected so we know how many options to re-enabled above
bonbonsCurrent += inputs[index].selectedIndex;
}
I'm an admitted newbie and am adapting a script from one ecommerce platform for another so am hamstrung in certain areas so feel free to make other suggestions.
here is one of possible solutions and the fiddle:
function chooseBon() {
var bonbonsAmount = 12;
var bonbonsCurrent = 0;
var bonbonsRemaining; //max. is bonbonsAmount
var inputs, i, j;
inputs = document.getElementsByTagName('select');
for (i = 0; i < inputs.length; i++) {
bonbonsCurrent += parseInt(inputs[i].value, 10);
}
bonbonsRemaining = bonbonsAmount - bonbonsCurrent;
for (i = 0; i < inputs.length; i++) {
for (j = 0; j <= bonbonsAmount; j++) {
inputs[i].options[j].disabled = (j < bonbonsRemaining + parseInt(inputs[i].value, 10) + 1) ? false : true;
}
}
}

How can I rewrite this without using JQuery library just with JavaScript?

I have a couple of lines of code in JQuery:
var central = $('#townid option:contains("Central")');
if (central.length){
central.insertAfter('select option:first-child');
}
How can I rewrite it without using JQuery library just with JavaScript?
A correct translation would be something like:
var selects = document.getElementsByTagName('select'),
options = document.getElementById('townid').getElementsByTagName('option'),
options = Array.prototype.slice.call(options), //2 lines only for readability
tmp = document.createDocumentFragment();
for(var i = 0, l = options.length; i < l; i++) {
var option = options[i],
text = option.innerText || option.textContent;
if(text.indexOf('Central') > -1) {
tmp.appendChild(option);
}
}
for(var i = 0, l = selects.length; i < l; i++) {
var select = selects[i],
opts = select.getElementsByTagName('option');
if(opts.length > 1) {
select.insertBefore(tmp.cloneNode(true), opts[1]);
}
else {
select.appendChild(tmp.cloneNode(true));
}
}
DEMO
This could be simplified a lot depending on the markup (and optimized depending on the browser (e.g. support for querySelectorAll)). E.g. if you know that there will always only be one option that contains "Central" and whether there exists only one select element or not.
Here is a stripped down version for one select element, known size of the list (i.e. > 1) and only one option that contains Central. So basically just reordering the option:
var options = document.getElementById('townid').getElementsByTagName('option');
for (var i = 0, l = options.length; i < l; i++) {
var option = options[i],
text = option.innerText || option.textContent;
if (text.indexOf('Central') > -1) {
if (i > 1) {
option.parentNode.insertBefore(option, options[1]);
}
break;
}
}
DEMO
Update:
If the option's text should be exactly Central, compare the text normally:
if(text === 'Central')

Categories

Resources