Can not find new elements after javascript append using chrome webdriver - javascript

Here's the simple HTML generated from a c# dotnet core asp pages, application. I'm trying to get the number of input boxes from colorList div using a webdriver test. The initial count of two works, but once i simulate the clicking the button labeled "+" i still only get two, where i expected to get three. I've tried all kinds of different waits both implicit and explicit, but can't seem to get it to work.
<!DOCTYPE html>
<html>
<head>
<title>Home page - SeleniumWebTest</title>
</head>
<body>
<div class="container body-content">
<body>
<form method="post" id="Form" action="/?handler=saveall">
<div><h4>Colors</h4><button type="button" onclick="CreateColor();" value="create" class="btn-sm">+</button></div>
<div class="indent" id="colorlist">
<input value="Red" type="text" id="Colors" name="Colors" /><br />
<input value="Blue" type="text" id="Colors" name="Colors" /><br />
</div>
<br />
<div>
<h1>More Stuff</h1>
</div>
<br />
<button type="submit" value="SaveAll" class="btn btn-primary">Save All</button>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Ps9gVily6NMr7L9g0lJf0cQzaqUzEq26TUrHCT4rH1GQIY0QLmjjc6cnQBE8aBvQlWdXAQZ2ub08pm2yIMWkUICO51XkWH6d11pf7y3pr3HwqRgBkiFdpaHSFYQsJsWdLba01RGCL8yYsUad9Vn2JQ" /></form>
</body>
<script type="text/javascript">
function CreateColor() {
var form = document.getElementById("colorlist");
var input = document.createElement("input");
input.type = "text";
input.id = "ColorId";
input.name = "ColorName";
form.appendChild(input);
linebreak = document.createElement("br");
form.appendChild(linebreak);
};
</script>
</div>
</body>
</html>
Here's my test
[Fact]
public void ColorTest()
{
var _driver = new ChromeDriver();
_driver.Navigate().GoToUrl("https://localhost:44394/");
Assert.Equal("Home page - SeleniumWebTest", _driver.Title);
var colorInputs = _driver.FindElements(By.Id("Colors"));
Assert.Equal(2, colorInputs.Count);
var plusButton = _driver.FindElement(By.XPath("//button[text()='+']"));
plusButton.Click();
var colorInputs2 = _driver.FindElements(By.Id("Colors"));
Assert.Equal(colorInputs.Count+1,colorInputs2.Count); // <-- Fails
_driver.Close();
_driver.Quit();
}

Yikes, after creating the question i see the problem. The id's for the new elements were being generated differently for razor pages versus javascript.

Related

PHP mysql data vs js dynamic fields

I have a piece of code (in a .php file) that can dynamically add/remove a group of input fields by JavaScript.
<!DOCTYPE html>
<!-- ref: https://stackoverflow.com/questions/75408002/javascript-dynamically-add-and-remove-input-fields -->
<html lang="en">
<head>
<style>
#template #template_p{ display: none }
</style>
</head>
<body>
<form action="" method="post" autocomplete="off">
<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<div id="placeholder">
<div id="template">
<fieldset id="template_fieldset">
<legend>Group</legend>
<p>Item <input type ="text" name="prof_item[]" /><br /></p>
<p>Duration <input type ="text" name="prof_duration[]" /><br /></p>
<p id="template_p"><button type ="button" name="prof_remove[]" onclick="this.closest('div').remove()">Remove group</button><br /></p>
</fieldset>
</div> <!-- template -->
</div> <!-- placeholder -->
<p><button type="button" name="add" onclick="Add();">Add new group</button></p>
</fieldset>
<p><button type="submit" name="Submit">Submit</button></p>
</form>
<script>
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder").appendChild(oClone);
}
</script>
</body>
</html>
Using this and adding some PHP code, user data can be collected and saved into MySQL. When the user comes back, is it possible to add the ability to populate the loaded user data into the page, and the user can still dynamically add/remove a group of input fields? I understand that PHP is run on the server and JavaScript is on the client side.

Clear submitted form using JavaScript

I know this is continuously asked anew, and I've checked out different answers and tried different solutions but to no avail.
I just have to build a form that takes as input the cylinder ray and it height and then find the volume when we click a button.After finding it, shuold be cleared all fields with another button .The function to calculate volume it is working fine, but not the function that clear inputs.
Here is the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript">
function llogarit() {
var rreze = parseInt(document.getElementById("val1").value);
var lartesi = parseInt(document.getElementById("val2").value);
var rez = document.getElementById("llogarit");
rez.value = (Math.PI * Math.pow(rreze, 2) * lartesi);
}
function fshij() {
document.getElementById("val1").value.clear();
document.getElementById("val2").value.clear();
document.getElementById("llogarit").value.clear();
}
</script>
</head>
<body>
<form>
<p>Vendos 2 vlera</p>
<p>rreze
<input type="text" name="rreze" id="val1" value="2" /></p>
<p> lartesi
<input type="text" name="lartesi" id="val2" value="2" /></p>
<p> Vellimi
<input type="text" name="vellimi" id="llogarit" value="" /></p>
<input type="button" onclick="llogarit()" value="llogarit" />
<input type="reset" value="fshij" onclick="fshij()" />
</body>
</html>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
You can reset all form controls in one form with reset method.
// <form name="FORM_NAME">
document.forms["FORM_NAME"].reset();
Try the following:
document.getElementById('myInput').value = ''
Try the follow and add a div tag to the code
<div class="yourClass">
<button onclick="cdClear();" class="yourClass">Clear</button>
</div>
Note: In HTM, you can replace the class with id if you have already coded.
<script type="text/javascript">
function cdClear(){var a=document.getElementById("codes");a.value="",a.focus(),</script>

Create a new <div> with .createElement()

Hi I'm new to Javascript, having problem creating and adding a new to the DOM. (I want to do this with native javascript not jquery).
When I click the "Calculate" button, I very briefly see the Text flash on the screen and then disappear. Nothing added to the DOM.
Here is my JS script:
function makeResponseBox() {
document.getElementById("calculate").onclick = function()
{
var responseBox = document.createElement("DIV"); //create <div>
var para = document.createElement("P");//create <p>
var text = document.createTextNode("Text");//
para.appendChild(text);//append text to para
var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
document.body.appendChild(newDiv);//append as child to <body>
}
}//close function (makeResponseBox)
window.onload=makeResponseBox;
Here is my HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add Element to DOM</title>
<script src="calculate.js"></script>
</head>
<body id="main">
<h1>Add Element to DOM</h1>
<form id ="form">
<fieldset>
<input type="submit" value="Calculate" id="calculate" />
</fieldset><!-- close fieldset -->
</form><!-- close form -->
</body>
</html>
It's because the form is submitted so the page is reloaded
You need to add a parameter to your listener , say function(e) and call e.preventDefault() at the beginning of the listener.
example:
document.getElementById("calculate").onclick = function(e)
{
e.preventDefault();
var responseBox = document.createElement("DIV"); //create <div>
var para = document.createElement("P");//create <p>
var text = document.createTextNode("Text");//
para.appendChild(text);//append text to para
var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
document.body.appendChild(newDiv);//append as child to <body>
}
Or you could also change the type of your button to remove the submit function
<input type="button" value="Calculate" id="calculate" />
But then your <form> become useless and you could remove it
change your submit type to button which will avoid the reload
<input type="submit" value="Calculate" id="calculate" />
to
<input type="button" value="Calculate" id="calculate" />
and if you want to submit the form handle it from js

Changing the text/background color through JavaScript immediately changes back

Trying to change text color and background color of the text according to what I write in the textbox. Seems to work briefly; it shows me the color for a split second, like a quick snap and that's it.
<!DOCTYPE html>
<html>
<head>
<title>Prelab5 Ex1</title>
<style>
</style>
</head>
<body>
<h2>Prelab5 Ex1</h2>
<form method="post">
<input type="text" name="background" id="background"/><input type="submit" value="Background" onclick="changeBack();"/>
<br/>
<input type="text" name="text" id="text"/><input type="submit" onclick="changeText();" value="Text"/>
<br/>
<div id="content">Some text</div>
</form>
<script>
var DivText = document.getElementById("content");
function changeBack(){
var backColor = (document.getElementById("background").value);
DivText.style.backgroundColor= backColor;
}
function changeText(){
var textColor = (document.getElementById("text").value);
DivText.style.color = textColor;
}
</script>
</body>
</html>
Your onclick handlers for your submit buttons don't return false so your form is submitted resetting the page. You could add return false like
var DivText = document.getElementById("content");
function changeBack() {
var backColor = (document.getElementById("background").value);
DivText.style.backgroundColor = backColor;
}
function changeText() {
var textColor = (document.getElementById("text").value);
DivText.style.color = textColor;
}
<!DOCTYPE html>
<html>
<head>
<title>Prelab5 Ex1</title>
</head>
<body>
<h2>Prelab5 Ex1</h2>
<form method="post">
<input type="text" name="background" id="background" />
<input type="submit" value="Background" onclick="changeBack(); return false" />
<br/>
<input type="text" name="text" id="text" />
<input type="submit" onclick="changeText(); return false" value="Text" />
<br/>
<div id="content">Some text</div>
</form>
</body>
</html>
Your "submit" input performs the action on the form, which is currently set to "post". This will post the form to the same page (and cause a refresh).
You can override the default functionality by adding return false; to the ONCLICK attribute on all input type= "submit" elements.
In other words, this:
needs to become this:
<input type="submit" onclick="changeText();" value="Text"/>
but why use input type = submit at all?
You can just as easily use a link or button without the form:
<a href="#" onclick="changeText();"/>Test</a>
or
Click me!
which will do the same thing without needing to override the a forum action :)

Replace text on button click

I'm looking for some code that will allow me to click a button (Button with value "Next") which will then replace some of the code I have on my page with new code. This is my current code, I need to replace everything after the score counter. Apologies for the sloppy code, I'm pretty new to this.
<body>
<p>Score: <span id="counter">0</span></p><br/>
<p>1) What colour is this?</p><br />
<p><img style= "margin: 0 auto;" src="colour1.png" width="70%"></p><br /><br />
<p><button id="none" onClick="showDiv01()">Almond White</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">Raspberry Diva</button><br>
<button id="none" onClick="showDiv01()">Melon Sorbet</button><br>
<button id="none" onClick="showDiv01()">Gentle Lavender</button><br></p>
<div id="answer1" style="display:none;" class="wronganswer">✗</div>
<div id="answer2" style="display:none;" class="rightanswer">✓</div>
<p><input type="button" name="next2" value="Next" onClick="showDiv2()" /></p>
</body>
try the below fiddle i am not sure its perfect u want or not but just tried
<body>
<p>Score: <span id="counter">0</span></p><br/>
<div id="div1">
<p>1) What colour is this?</p><br />
<p><img style= "margin: 0 auto;" src="colour1.png" width="70%"></p><br /><br />
<p><button id="none" onClick="showDiv01()">Almond White</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">Raspberry Diva</button><br>
<button id="none" onClick="showDiv01()">Melon Sorbet</button><br>
<button id="none" onClick="showDiv01()">Gentle Lavender</button><br></p>
</div>
<div id="div2" hidden>
1) What car is this?</p><br />
<p><img style= "margin: 0 auto;" src="colour1.png" width="70%"></p><br /><br />
<p><button id="none" onClick="showDiv01()">abc</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">def</button><br>
<button id="none" onClick="showDiv01()">rtrt</button><br>
<button id="none" onClick="showDiv01()">xyz</button><br></p>
</div>
<div id="answer1" style="display:none;" class="wronganswer">✗</div>
<div id="answer2" style="display:none;" class="rightanswer">✓</div>
<p><input type="button" id="btn" name="next2" value="Next" onClick="showDiv2()" /></p>
</body>
$('#btn').click( function() {
$("#div1").hide();
$("#div2").show();
});
http://jsfiddle.net/uxyQG/
If you want to replace the text on button click. I checked you button have an onClick="showDiv2()"
So try like this (for an example)
function showDiv2 () {
document.getElementById('counter').innerHTML = ""; //empty the value
}
Here is example fiddle, I have create when you click next the counter will be replaced.
What you want to do here is place all the content you want to replace inside a <div>.
then you will want to give that div an id attribute.
e.g.
<div id="yourID">
HTML CONTENT HERE
</div>
Then in javascript, you would need to create a function that would fire on an onclick event.
Markup:
<input type="button" onclick="changeContent('yourID', '<div>OtherHTML</div>')" value="NEXT" />
when you have these 2 components, you will want to make a script that will execute your function.
<script type="text/javascript">
function changeContent(id, html) {
//Get the element that needs it's contents replaced.
var container = document.getElementById(id);
//insert new HTML onclick.
container.innerHTML = html;
}
</script>
This is a simple example of what you need.
You could externalize this javascript in a seperate file.
If you want to do this, you will need to include the script in the <head> of your html document.
<script type="text/javascript" src="path/to/js.js"></script>
Because this will load before any of the DOM will have been loaded, you will get errors.
To solve this, the new contents of the file will be:
js.js
window.onload = function() {
function changeContent(id, html) {
//Get the element that needs it's contents replaced.
var container = document.getElementById(id);
//insert new HTML onclick.
container.innerHTML = html;
}
}
This should work for you in this scenario.
Hope this helped
&dash; Sid

Categories

Resources