Selenium Input text does not replace all the values - javascript

I am providing an input which is suppose to replace the old values at two tabs. The values are auto populating one at one tab but I am providing them completely without using auto populate feature.
The value is getting replaced only at one tab and not at the other tab. The second tab shows the xml version of the first tab.
Code of the page
Tab 1 where I am providing input
AllElements = driver.find_elements_by_xpath("//div[#class='CodeMirror cm-s-
codeedit CodeMirror-wrap']")
for row in Inputs:
Content = row['Content']
Universe = row['Universe']
for ele in AllElements:
count = count + 1
if count == 1:
ele.click()
#Content = 'TR.NetAssetEstBrokerName'
driver.execute_script('return arguments[0].setAttribute("style",
"visibility:visible")', ele)
driver.execute_script("arguments[0].innerText = ' " + Content +
" ' ", ele)
driver.execute_script('return
arguments[0].setAttribute("value",' + Content + ')',
ele)
if count == 2:
ele.click()
#Universe = 'IBM.N#RIC'
driver.execute_script('return arguments[0].setAttribute("style",
"visibility:visible")', ele)
driver.execute_script("arguments[0].innerText = ' " + Universe +
" ' ", ele)
driver.execute_script('return
arguments[0].setAttribute("value",'+Universe+')', ele)
driver.find_element_by_id('button-1093-btnEl').click()

It is because you are using javascriptexecutor. It directly changing the value from DOM. If you want your functionality should behave as per business logic use operation like setAttribute which can behave as required:
driver.findElement(By.id("YOURID")).setAttribute("value", "your value");

Related

How to prevent appending multiple times in the table, Once It forcing to double click multiple times the table row using Jquery?

I have module appending the result of response to the other table. looking forward I found a solution in my module. however I found problem on that i will give to you guys the scenario what the problem it does.
First Scenario:
User will choose what condiment he wanted to click, Looking forward Ex. User 1 choose the Second table row, the Condiments *LG FRIES.
Second Scenario:
In the first scenario user choose the *LG FRIES, as you can see here modal will open and the result of response will append to the table B.
Third Scenario: Well First and Second scenario look works and good, but here I will show you, how does appending will multiply in the table once i force double click the table row of *LG FRIES.
So now i will let you show my codes.
This is my function for getting the result of clicking the of table row then the result will append to the table B.
$('table#noun_chaining_order').on('click','tr.editCondiments',function(e){
var allow_to_open_condiments_conditional = $(this).closest("tr").find(".allow_to_open_condiments_conditional").text();
if(allow_to_open_condiments_conditional == 'Yes') {
$('.conditional_table_hidden_noun').hide();
$('.conditional_table_hidden_condiments').show();
$('table#noun_chaining_order tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_condiments = $(this).find('td.condi_section_id').text();
$("table#customer_table_update_chain_order tbody").html('');
$('#customer_modal_update_chain_order').modal('show');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#customer_table_update_chain_order tbody').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
},
error:function(response){
console.log(response);
}
});
}
else
{
}
});
So the question will be, How to stop appending multiple times once I force double click the table row?
I see simple solutions here.
When you appending cart item, you can add that item ID from database
to the element. And before appending check if an item from response
doesn't exist in BODY.
Another solution will be just after you click append - hide that CTA
(button)to prevent it from another click.
Check your database for multiple records.
Anyways, please check when you do ajax request? after click?
Have you tried to debug your code with breakpoints? or console?

LocalStorage element not corresponding with visual element after moving

I created a note-taking front end page which saves the data from text field into the localStorage. The problem occurs when the user deletes one field using the Delete button, which corresopndents to DeleteT function.
For example if we have three textareas with id txt1, txt2, txt3 they apper with the sames names in the localStorage. After the user deletes for example txt2 using the Delete button, in the local Storage the left ones are txt1 and txt3 but on the next reload there are two textareas with id txt1 and txt2 because in the localStorage the number of textareas is saved by key AllNum. The data from txt3 in the localStorage should go to txt2 in the DOM on the page.
The problematic functions:
// Deletes textelemnt
function DeleteT(num) {
localStorage.removeItem("txt" + num);
localStorage.removeItem("h" + num);
console.log('del');
i=i-1;
var now = localStorage.getItem("AllNum");
if((now-1)<0){
now=0;
localStorage.setItem("AllNum", (0));
}else{
localStorage.setItem("AllNum", (now-1));
}
$("div.textarea" + num).remove();
}
//Loads all the text elemnts with a for loop until the number of areas is reached
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea' + i + '"><input onkeyup="save()" id="h' + i + '"></input><textarea onkeyup="save()" id="txt' + i + '"></textarea></br><button onClick="cut(txt' + i + ')" class="f b">Cut</button> <button onClick="copy(txt' + i + ')" class="f b">Copy</button> <button onClick="speak(txt' + i + ')" class="f b">Speak</button> <button onClick="download(' + i + ')" class="f a">Save</button><button onClick="textFull(' + i + ')" class="f">Fullscreen</button> <button onClick="DeleteT(' + i + ')" class="f">Delete</button> </div>');
document.getElementById('txt' + i).innerHTML = localStorage.getItem("txt" + i);
document.getElementById("h" + i).setAttribute('value', localStorage.getItem("h" + i));
}
}
}
https://codepen.io/abooo/pen/NoqOXX?editors=1010
To experience the problem create three textareas using the + button. Then Enter data in the them. After this delete the latter. Finally reload the page and make sure the two textreas appeared. You can see the data from the second one is missing replaced with null value. How to fix this issue?
The result
LocalStorage values
The value "AllNum" only stores total number of items; it does not contain any information about which items were there before reloading. So in first load, if you add 3 items and remove the 2nd, your local storage will have "AllNum" equal 2, and the next time it loads, your load() function will iterate from 1 to 2, looking for data of text1 and text2. That's why only 1st item displays correctly.
Another problem that you might notice after fixing the above issue is that the iteration is not good for unique id; a simple test can prove it: you add 3 items, remove the 2nd - now you have text1 and text3 in localStorage, and AllNum is 2. If you add one more, the newest item will have id as 3 and all its data will be written on top of the existing text3 and h3.
2 suggestion for your code:
Use something else as unique id instead of iteration number. Use Math.random(), for example.
Store all your unique ids in localStorage, not AllNum. Rewrite your code to add and delete unique ids from localStorage.
A small example of how to modify the 2 function add() and save():
function add() {
var newId = Math.random();
// your render logic here. Replace i with newId
save(newId);
}
function save(newId) {
localStorage.setItem("txt" + newId, document.getElementById('txt' + a).value);
localStorage.setItem("h" + newId, document.getElementById('h' + a).value);
var allIds = JSON.parse(localStorage.getItem('AllIds'));
allIds.push(newId);
localStorage.setItem("AllIds", JSON.stringify(allIds));
}

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

javascript not adding html div to string

I'm working with a wordpress plugin called Wordpress Simple Paypal Shopping Cart, when the form is sent it starts this script. It takes a product, and three dropdown and puts them into a format in one string like this:
SHOP ITEM (dropdown1) (dropdown2) (dropdown3)
Here is the code.
<script type="text/javascript">
<!--
//
function ReadForm (obj1, tst)
{
// Read the user form
var i,j,pos;
val_total="";val_combo="";
for (i=0; i<obj1.length; i++)
{
// run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one")
{ // just selects
if (obj.name == "quantity" ||
obj.name == "amount") continue;
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
val_combo = val_combo + " (" + val + ")";
}
}
// Now summarize everything we have processed above
val_total = obj1.product_tmp.value + val_combo;
obj1.product.value = val_total;
}
//-->
</script>';
I need to change the output so I can style the three options with specific CSS. The output in HTML is in a span.
I notice the line val_combo = val_combo + " (" + val + ")"; adds the brackets around the output so I tried to change it to val_combo = val_combo + " <div>" + val + "</div>"; but the output strips the divs, leaving the output like:
SHOP ITEM dropdown1 dropdown2 dropdown3
I'm not clever with Javascript so any examples as if for a child would be highly appreciated.

js/jquery iterate through html elements to dynamically build a string

I'd like to build a string based on values defined in an html form only if they have been populated. I've successfully parsed the form fields and dropdown with a for loop ($.each()) but my ultimate goal is to dynamically build a string with the results. The string is being used to create a REST query, this is currently the only way to search based on our technologies. Does anyone have a recommended solution?
thx in advance
sample html element:
<input data-param=" prefix like '%" data-name="prefix" class="prefix uno" type="text" placeholder="pre">
working btn click event loop to capture filled in form fields:
var children = $(this).parent().children('.uno');
$.each(children, function(i, val){
if($(val).val() !== ''){
console.log($(val).data('name') + " "+ $(val).data('param') + " " + $(val).val());
}
});
goal:
var newString = field1.param + field1.val + '% ' + field2.param + field2.val + '% ';
translated:
var newString = prefix like '%01%' and name like '%tree%';
Thanks David Fregoli for the jquery serialize reference, that was close, but the solution ended up being to place the strings into a single array, change it toString(), and remove the ',' from the new string.
code:
var samp = [],
thisVal = $(this).parent().children('.uno');
$.each(thisVal, function(i, val){
if($(val).val() !== ''){
samp.push(
$(val).data('param'),
$(val).val(),
$(val).data('close')
);
}
});
itQuery.where = samp.toString().replace( /,/g , '');
result search string:
"number like '%08%' and field = 34"

Categories