I have select elements as below
<select name="selectid1" id="selectid1" onChange="script.selectChange(this,'tr');">.......</select>
and
<select name="selectid2" id="selectid2" onChange="script.selectChange(this,'div');">.......</select>
I want to extract the selectChange method's String paramter (the 2nd paramter) tr and div of the onChange attribute of both the select elemets using regular expresssion.
I can get the value of onChange using
var selectid1 = $('#selectid1').attr('onChange'); //script.selectChange(this,'tr');
and
var selectid2 = $('#selectid2').attr('onChange'); //script.selectChange(this,'div');
What regex should I use in order to get strings 'tr' and 'div' from the variables?
If it's just for test case - use the following approach with String.match function:
var selectid1 = "script.selectChange(this,'tr')",
param = selectid1.match(/,\s?['"]([^)]+)['"]/)[1];
console.log(param); // tr
/onChange="script.selectChange\(this,'([^']*)'/g
Demo here --> https://regex101.com/r/uW2aQ6/1
Related
I'm creating an online shop, with specific links to products e.g. (http://example.com/products/phones/nexus-5).
I'm using the following code,
var get_product_availability_classname = $("[class$='_availability']").attr('class');
which selects (creates a variable with the value of) the element that has a class ending in "_availability".
Every product page has a different piece of text just before the _availability, like GOOGLENEXUS5_availability, SAMSUNG4KTV_availability, whatever_availability...
What I have to do now is to essentially remove the criteria I used to get that whole class name (i.e. class$='_availability'); using the example above it'd be trimmed from SAMSUNG4KTV_availability to SAMSUNG4KTV.
Possible solutions
I haven't figured how to, but we could use JavaScript's substring() or substr().
You will be best off using Regex in this situation. The following will look for the _availability in the classes string and if it finds it it will capture what came before.
var get_product_availability_classname = $("[class$='_availability']").attr('class');
var matches = /([^\s]*)_availability\b/g.exec(get_product_availability_classname)
if(matches.length > 1){
var your_id = matches[1];
}
Use attr() method with a callback and update the class name using String#replace method with word boundary regex.
Although use attribute contains selector since there is a chance to have multiple classes, in that case, the class can be at the start or between two classes.
var get_product_availability_classname = $("[class*='_availability '],[class$='_availability']");
get_product_availability_classname.attr('class',function(i,v){
return v.replace(/_availability\b/g,'');
});
var get_product_availability_classname = $("[class*='_availability '],[class$='_availability']");
get_product_availability_classname.attr('class', function(i, v) {
return v.replace(/_availability\b/, '');
});
console.log(document.body.innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="abc_availability"></div>
<div class="abc_availability class"></div>
<div class="class abc_availability"></div>
<div class="class abc_availability class1"></div>
If there will only ever be a single _ in the class name
var get_product_availability_classname = $("[class$='_availability']").attr('class')
.split(' ') // split the class to individual classes
.filter(function(cls) { // filter ones with _availability
return cls.split('_').pop() == 'availability');
})[0]; // use first match
var product = get_product_availability_classname.split('_')[0]
.split('_') creates an array ["PRODUCT", "availability"] and the [0] selects the first item of this array
alternatively you could also
var product = get_product_availability_classname.split('_availability')[0]
this does the same thing, except it splits on the string _availability, and it doesn't matter how many _ in the prefix
If your string is always in the form x_y, where x and y don't contain an underscore, then you can use the split function to split on the underscore.
var str = "SAMSUNG4KTV_availability";
var result = str.split("_")[0];
console.log(result);
The split function returns an array of strings containing the substring in between each underscore, you use [0] to select the first element in the array.
I am trying to execute a javascript using python selenium. I am basically trying to set the value using execute.script but somehow is it not doing anything. I want to edit the street address as you see below
execute_script(driver, """var element = document.getElementsByClassName('input[ng-model="formData.address.address1"]'); element.value = '328 91st Street'; """)
Could anyone tell me what's the issue here? I am not getting an error also
There is a more robust way of doing it - locating the element with selenium using a CSS selector and passing the WebElement as well as a value into the script as an argument:
elm = driver.find_element_by_css_selector('input[ng-model="formData.address.address1"]')
value = '328 91st Street'
driver.execute_script("arguments[0].value = 'arguments[1]';", elm, value)
Note that in your code, you have 2 major problems:
you are passing a CSS selector into the getElementsByClassName() call - instead, it expects you to pass a class name as a string
getElementsByClassName() returns an array of elements and not a single element
This code is almost good to go...
execute_script(driver, """var element = document.getElementsByClassName('input[ng-model="formData.address.address1"]'); element.value = '328 91st Street'; """)
Just remember that getElementsByClassName will return an array...
And I guess you should use querySelector or querySelectorAll function...
// will select just one element
var element = document.querySelector('input[ng-model="formData.address.address1"]');
// will select all elements
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
getElementsByClassName you should inform a class... (I think it's hard to have a class like: ng-model="formData.address.address1")
Using querySelector
var element = document.querySelector('input[ng-model="formData.address.address1"]');
element.value = '328 91st Street';//Work!!!
In case you want to iterate in these NodeLists with querySelectorAll
Basically,
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
element.value = '328 91st Street';//WON'T WORK
Do instead:
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
element[0].value = '328 91st Street'; // change the value for the first element
for(int i = 0 ;i<element.length;i++){ //change all elements
element[i].value = '328 91st Street';
}
I have a click event listener as below:
$(".clickable").click(function (e) {
var results= $(e.currentTarget).closest('div.set').find('.clickable');
// returns
//[<label for="thumbnail" class="clickable">1 Malaysia</label>,
//<div class="thumbnail clickable">…</div>]
var label = $(results).find('label'); // returns [] (empty list)
}
My problem is, how can I select the label element from the results list ? Thanks !
Try to use .filter() instead of .find(),
var label = results.filter('label');
.find() will search for descendants, but here we are in need to filter out the required element from the collection, so use .filter(selector) here.
And also you could have simply used as satpal said like,
var results= $(e.currentTarget).closest('div.set').find('label.clickable');
I have an attribute for a set of HTML5 objects that is an array. Something like
<button attr=[1,0,0,0,1,1]>test</button>
<button attr=[1,1,0,0,1,1]>test</button>
...
How do I formulate a jQuery selector to match only elements whose n-th value of attr is 1? Something like $("attr[1]=1") that would only select the second button from this example (this syntax does not work, but I wrote it just to give an idea of what I need).
In my case I am not dealing with buttons but with other types of objects, I just wanted so simplify the context of the question.
You can use a custom filter to select only the matched elements.
<button data-attr="[1,0,0,0,1,1]">button 1</button>
<button data-attr="[1,1,0,0,1,1]">button 2</button>
Note that attr is not a valid html attribute for button. I'd suggest you use the data-attr instead. You can use .data('attr') to get the data back.
var selected = $('button').filter(function (idx) {
var attr = $(this).data('attr');
return attr && attr[1] == 1;
});
alert(selected.html());
jsFiddle Demo
You can write your own selector like this (i called it "array", you can use a better name here):
jQuery.expr[':'].array = function (elem, index, match) {
var params = match[3].replace(/^\s+|\s+$/g, '').split(/\s*,\s*/),
attribute = params[0],
arrayindex = parseInt(params[1]),
matchvalue = params[2],
value = JSON.parse($(elem)[attribute](attribute));
return value[arrayindex] == matchvalue;
};
Then, use it like any other selector where the first parameter is the name of the attribute, the second parameter is the index in your array and the third parameter is the expected value:
$('button:array(attr,1,1)');
Fiddle: http://jsfiddle.net/pascalockert/uDnK8/2/
I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');