JS : .prepend() an option to 2 select doesn't work - javascript

I hope the title is self explanatory but i'll try to explain my problem nonetheless.
in my HTML file, i have 2 select, with no option. On the page load, a ajax request is performed to fetch some datas. In the success callback of my Ajax request, i create an option element for every data i just got. I also prepend those newly created option element to both of my select, but the only prepend that works is the one done on the last select
Here are SC of my code, in this examlple, the option have been prepended on the into_APPNAME select only, and not into the from_APPNAME. If i would revert the prepend such as
$("#into_" + repoName).prepend(option)
$("#from_" + repoName).prepend(option)
only from_APPNAME select would have got options in it.
Any ideas what's going on ?

You have to create two different HTML elements or clone the first one you created in order to create a new one. This code for example should populate both of them:
var option1 = $('<option></option>').attr('value', branch).text(branch);
var option2 = $('<option></option>').attr('value', branch).text(branch);
$("#into_" + repoName).prepend(option1);
$("#from_" + repoName).prepend(option2);
Of course better to clone the option1 into the option2
var option2 = $(option1).clone();
Another way can be the following, getting rid of variables:
$("#into_" + repoName).prepend($('<option></option>').attr('value', branch).text(branch));
$("#from_" + repoName).prepend($('<option></option>').attr('value', branch).text(branch));

Related

How to select a value from dropdown with Selenium?

This is the source code :
<select name="backgroundcolor" onchange="backgroundColor();">
<option value="200">Red</option>
....
</select>
I tried below code in order to select the "Red" option but it didn't work.
Select dropDown = new Select(driver.findElement(By.name("backgroundcolor")));
dropDown.selectByValue("200");
I'm getting NoSuchElementException Exception
Unable to locate element //*[name='backgroundcolor']
try this
Select select = new Select(driver.findElement(By.name("backgroundcolor")));
select.deselectAll();
select.selectByVisibleText("Red");
perhaps the By.name is the problem, i am used to using something like :
By.xpath("//path_to_drop_down"))
try this, you need to convert the below code to the language you are using
from selenium.webdriver.support.select import Select as WebDriverSelect
element = WebDriverSelect(driver.find_element_by_name('backgroundcolor'))
element.select_by_value('200')
You note that it's possibly a timing issue. If so, you'll need to wait until the element appears on the page. Try this:
By locator = By.name("backgroundcolor");
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
Select dropDown = new Select(driver.findElement(locator));
dropDown.selectByValue("200");
I got " Unable to locate element *[name='backgroundcolor'] " error.I solved that problem when firstly I try to reach the iframe which contain that dropdown.It's a timing issue by the way.
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(theindexofframe));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("backgroundcolor")));
You should wait for the iframe to be loaded after that you should wait for the "backgroundcolor" element to be loaded also.After that you can select the value from dropdown like this:
Select dropDown = new Select(driver.findElement(By.name("backgroundcolor")));
dropDown.selectByValue("200");

selecting drop-down option of variable which contain html

A variable contains html
var empDaysStatusDropDown =
"<select class='statusList form-control'><option value='1'>Official On</option><option value='2'>Official Off</option><option value='3'>Sick Leave</option><option value='4'>Casual Leave</option><option value='5'>Annual Leave</option></select>"
I want to update this html through programming by selecting any of the dropdown option?
Means I want to select any of the option either 0,1,2,3 of dropdown and update html accordingly so that as I show that html on page the option will see selected which i select first
Try this
$(document.body).on("change",".statusList",function(){
if(".statusList option:selected").val()=="1"){
empDaysStatusDropDown ="new html";
}
})
Edit:
I have also created the fiddle for it : Demo
According to me you need to implement it before appending it to the page. So you want to manipulate it in jquery, Here we go:
var empDaysStatusDropDown =
$("<select class='statusList form-control'><option value='1'>Official On</option><option value='2'>Official Off</option><option value='3'>Sick Leave</option><option value='4'>Casual Leave</option><option value='5'>Annual Leave</option></select>");
empDaysStatusDropDown.find('option[value="1"]').attr('selected','selected');
// now you can append empDaysDropDown anywhere on the page.
$('body').append(empDaysStatusDropDown);
Hope this helps :)

Catch all radiobuttons inside a div using jQuery

Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well

Issue in select option in Jquery mobile

I have a table which contains input text and select option and button.The table row is cloned when the button is clicked. Every thing is working fine except the select option. After the table row is cloned the select option not display what i select. Here is the JsFiddle http://jsfiddle.net/aravinth/Ad22d/
Javascript code like
var b = 1;
function cloneRow() {
var row = document.getElementById("table");
var table = document.getElementById("particulars");
var clone = row.rows[1].cloneNode(true);
var clones = row.rows.length;
var workerName = clone.cells[0].getElementsByTagName('input')[0];
var position = clone.cells[2].getElementsByTagName('select')[0];
var date1 = clone.cells[3].getElementsByTagName('input')[0];
var fromHr = clone.cells[4].getElementsByTagName('input')[0];
var toHr = clone.cells[5].getElementsByTagName('input')[0];
var add = clone.cells[1].getElementsByTagName('input')[0];
workerName.id = "workerName" + b;
position.id = "position" + b;
date1.id = "date1" + b;
fromHr.id = "fromHr" + b;
toHr.id = "toHr" + b;
add.id = "add" + b;
$(date1).datebox();
table.appendChild(clone);
b++;
}
Also i referred this
1 . Change Select value using jQuery Uniform.js
2 . jquery cloning a block of element. select element acting weired
3. select not working after .clone
but not get success. Please suggest some solutions.
It seems, jQuery mobile doesn't recognize the cloned selectmenu.
What you can do, is remove the selectmenu and re-add only the HTML select and then initialize it with selectmenu()
$('.ui-select', clone).remove();
clone.cells[2].appendChild(position);
$(position).selectmenu();
See modified JSFiddle
Update:
I just followed jquery cloning a block of element. select element acting weired and found #malko's answer, which is a lot more elegant than removing and reinserting. This reduces it to
$(position).closest('.ui-select').replaceWith(position);
$(position).selectmenu();
See JSFiddle
I think you solved select option issue by using this answer. And another one issue you need to fix in your fiddle. The issue is time picker for last two columns (fromHr and toHr).
To fix this you need to add the bellow lines in your javascript code.
$(fromHr).datebox();
$(toHr).datebox();
because those rows are dynamically created. So you need to add the above lines to show time picker in your fromHr and toHr.
See this working FIDDLE
The issue is that jQuery Mobile recreates a lot of elements, for example your select, to be non-native widgets, and then binds functions to certain events. When you just clone the row, you aren't getting the event-bindings, so what you need to do is actually append the raw html -- what it was before it got re-rendered -- and then trigger the create method:
var template="<tr><td>..your row here..</td></tr>";
$("#particulars").append(template).parent().trigger('create');
I have a barely working fiddle, but I removed a lot of your code so I could easily illustrate what I am talking about.
http://jsfiddle.net/Ad22d/81/
I had the same issue and fixed it by calling selectmenu("destroy") on the original select box before cloning, and then re-initializing select boxes by calling selectmenu() after cloned select is appended.

create a new option and inject into select box using mootools 1.2

i have one AJAX function which return the list of countries. It works fine.
My problem is that want to load that countries in on select box which is already in HTML and is empty means no option value in it.
I want to know that how can i create a new option element and inject into the select box using moo tools 1.2
I have used below code but its not working in IE.
var NewOption = new Option("Select Sub Category",'0');
NewOption.inject($('nSub_nIndustryID'))
Thanks
Avinash
There is no need to create a variable, unless you are going to use it later.
new Element('option', {'value': 0, 'text':'Select states first'}).inject($('sCity'));
i have solved it my self..
var newElement = new Element('option');
newElement.inject($('sCity'));
newElement.setProperty('value','0');
newElement.appendText('Select States first');
Thx for your time....

Categories

Resources