CTRL+C not working in hidden <div> - javascript

I wanted to have a feature wherein the user can just copy the contents of a particular by just clicking a single button and press CTRL+C.
The following works if I don't put style="display: none" to my divToCopy. However, when I place the style, CTRL+C will no longer work.
var Clipboard = function() {
var clipboard = {};
clipboard.cssStyle = "";
clipboard.cssClass = "";
clipboard.targetId = "";
clipboard.highlight = function(targetId) {
// backup the styling of the target div
clipboard.cssStyle = $("#" + targetId).attr('style');
clipboard.cssClass = $("#" + targetId).attr('class');
// create a ranged selection
window.getSelection().removeAllRanges();
if (window.getSelection) {
console.log("has selection");
var node = document.getElementById("divToCopy");
var range = document.createRange();
console.log(range);
range.selectNodeContents(node);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
// highlight
$("#" + targetId).css("background-color", "yellow");
};
clipboard.copyWithStyle = function(targetId) {
var toCopy = $('#' + targetId).html();
$('#divToCopy').html(toCopy);
clipboard.targetId = targetId;
clipboard.highlight(targetId);
};
clipboard.copyNoStyle = function(targetId) {
var toCopy = $('#' + targetId).html();
$('#divToCopy').html(toCopy);
$('#divToCopy *').removeAttr('style');
$('#divToCopy *').removeAttr('class');
clipboard.targetId = targetId;
clipboard.highlight(targetId);
};
$("#divToCopy").bind('copy', function() {
$("#" + clipboard.targetId).attr('style', clipboard.cssStyle);
$("#" + clipboard.targetId).attr('class', clipboard.cssClass);
});
return clipboard;
};
$(document).ready(function() {
var c = Clipboard();
$("#copy-with-style").click(function(event) {
c.copyWithStyle("content");
});
$("#copy-no-style").click(function(event) {
c.copyNoStyle("content");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-body" align="center">
<br/>
<div id="content" style="text-align:left; margin:0 auto; border: 1px solid black; width: 300px; padding: 5px;">
<div style="color:red">RED by Taylor Swift</div>
<ul>
<li>One</li>
<li style="font-weight:bold;">Two</li>
<li>3</li>
<li>Four</li>
<li>~!##$%^&*()______+{}[]:";'
<>?,./"</li>
</ul>
<table style="border:1px solid green;">
<tr>
<td colspan=2>Merged</td>
<td style="color:blue;">Blue</td>
</tr>
<tr>
<td>Red</td>
<td>Green</td>
<td>Violet</td>
</tr>
</table>
</div>
<br/>
<input type="button" value="Copy With Style" id="copy-with-style" />
<input type="button" value="Copy Without Style" id="copy-no-style" />
<div id="divToCopy" style="display: none" contenteditable="true"></div>
</div>

Instead of display:none; Use visibility:hidden This might work for you.

don't use:
display: none;
visibility: hidden;
use:
width: 1px;
height: 1px;
overflow: hidden;

Related

I was trying to make a to-do list using javascript but unable to append the selected option

Aim was to take input and create radio buttons and label dynamically like a list which when checked goes to bottom while label name coming from the input textfield that we write. I was able to do this with the radio button but not with the label. Please help me out I'm new here.
[Fiddle] (http://jsfiddle.net/wju6t7k3/2/)
<div id = "container" >
<div class="row">
<div class="col-12">
<input id = "txt" type = "text" placeholder="Add new.." >
<button id="btn" value = "add" type = "button" onClick = "add()" >
</button>
</div>
<div id="done" class="col-12">
</div>
</div> <!-- row -->
<script>
//js
var j = 0;
var textval="";
function getInputValue(){
// Selecting the input element and get its value
inputVal = document.getElementById("txt").value;
// Displaying the value
alert(inputVal);
}
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval =this.value;
onfocus=this.value='';
}
});
function countChecked(event) {
alert(textval);
alert("balle");
getInputValue();
$(this).parent().parent().append(this).append('<label>textvalh</label>').append('<br>');
}
$("#container").on( "click", "input[type=checkbox]", countChecked );
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
</script>
You have to make a container or a parent element for the checkbox and its label to have more control of it.
and if you want to separate the checkbox that is checked, then make another div element to make a separation.
Here's an example, this is based on your code:
//js
var j = 0;
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<div><input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label></div>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval = this.value;
this.value='';
}
});
function countChecked(event) {
const isChecked = event.currentTarget.checked;
// Get parent of checkbox which is the closest <div> element
const checkbox_parent = $(event.currentTarget).closest('div');
if (isChecked) // Move element to div with ID = selected
checkbox_parent.appendTo('#selected')
else // Move element to div with ID = done
checkbox_parent.appendTo('#done')
}
$('#container').on('change', 'input[type="checkbox"]', countChecked)
input, input:active{
border:none;
cursor: pointer;
outline: none;
}
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: blue;
}
::-moz-placeholder { /* Firefox 19+ */
color: blue;
}
:-ms-input-placeholder { /* IE 10+ */
color: blue;
}
:-moz-placeholder { /* Firefox 18- */
color: blue;
}
button{
display:none;
}
.checkbox-round {
width: 1.3em;
height: 1.3em;
background-color: white;
border-radius: 50%;
vertical-align: middle;
border: 1px solid #ddd;
-webkit-appearance: none;
outline: none;
cursor: pointer;
}
.checkbox-round:checked {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" >
<div class="row">
<div class="col-12" style="border: dashed red 3px;">
<input id = "txt" type="text" placeholder="Add new.." />
<button id="btn" value="add" type="button" onClick ="add()">Add</button>
<div id="done" class="col-12" style="border: solid purple 3px;">
</div>
<div id="selected" class="col-12" style="border: solid gray 3px;">
</div>
</div>
</div> <!-- row -->
</div>
Happy Coding!

Set the selector cursor to a new position in contenteditable div [duplicate]

This question already has answers here:
How to set the caret (cursor) position in a contenteditable element (div)?
(13 answers)
Closed 2 years ago.
i've been making a text editor but i couldn't been able to get and set the "cursor" in a new position in the div with the content editable.
<form action="submitchapter.php" method="post">
<div class="input-group mb-3" style="margin-top:30px;">
<input type="text" class="form-control name" placeholder="Chapter Name" name="sname" value="No Title For The Chapter" required>
</div>
<div class="buttons shadow-sm">
<button style="padding:0; border:0px solid white; background-color:white;" type="button" id="buttonbold"><i class="fas fa-bold" id="bold"></i></button>
<input id="file-input" type="file" name="name" style="display: none;" />
</div><br>
<div class="containe shadow-sm" style="padding:20px; background-color:white;">
<div class="content" contenteditable="true" name="content" id="content" role="textbox" spellcheck="false"></div>
</div>
var content = document.getElementById("content");
var bold = document.getElementById("bold");
var content = document.getElementById("content");
$("#buttonbold").click(function(){
content.focus();
var valuelength = content.value.length - 4;
content.setSelectionRange(content.value.length,valuelength);
});
var boldactive = false;
$("#bold").click(function(){
if (boldactive == false) {
var content1 = content.innerHTML;
content.innerHTML = content1 + "<b>";
boldactive = true;
} else {
var content1 = content.innerHTML;
content.innerHTML = content1 + "</b>";
boldactive = false;
}
});
But nothing worked. I have tried with textarea too, but I think I'm doing something wrong.
<div> elements have no value property
$("#buttonbold").click(function(){
content.focus();
var valuelength = content.textContent.length - 4;
content.setSelectionRange(content.textContent.length,valuelength);
});
.
<div> elements do not have a setSelectionRange method either,
so here is a solution to make this kind of selection for elements using the contenteditable property:
const myDiv = document.getElementById('my-div')
, btSelectRange = document.getElementById('bt-select-range')
;
function setSelectionRangeCE(el, pos, len)
{
el.focus();
let range = document.createRange()
, sel = window.getSelection()
;
range.setStart(el.firstChild, pos)
range.setEnd(el.firstChild, pos+len)
sel.removeAllRanges()
sel.addRange(range)
}
btSelectRange.onclick=_=>
{
setSelectionRangeCE(myDiv,2,5)
}
#my-div {
margin: 1em;
padding: .7em;
width: 16em;
height: 3em;
border: 1px solid grey;
}
button {
margin: 1em;
}
<div id="my-div" contenteditable >hello world</div>
<button id="bt-select-range" > select range pos:2 len:5 </button>

jQuery/JavaScript Get input values and then copy to clipboard

I have a bunch of input elements and with javascript on click i'm getting the values of these inputs and paste it in a div somewhere
Please run the code snipped below to check
$('#getthelist').click(function() {
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
$('.list').append('<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>');
});
});
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<div class="list"></div>
So i have got one question and a problem i cant figure out how to fix.
The problem is, each time you click the button it pastes the values in the div repeatedly. It is a mess to me for what i'm trying to do. so, How do i force it not to repeat the same values when you click every time.
Question: How do i copy the input values to clipboard with the same click function?
Please check my snippet codes.
function copyToClipboad(texts) {
var textareaElCloned = $('<textarea>' + texts + '</textarea>');
$('.list').append(textareaElCloned);
/* Select the text field */
textareaElCloned[0].select();
/* Copy the text inside the text field */
document.execCommand("copy");
}
$('#getthelist').click(function() {
var html = '';
var texts = '';
var itemEls = $('.inputs > li .color');
itemEls.map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e, index) {
var text = '\"' + e.name + '\": \"' + e.value + '\",';
texts += text;
html += ('<div>' + text + '</div>');
if (index === itemEls.length-1) {
copyToClipboad(texts);
}
});
$('.list').html(html); // the textarea will be removed at this moment
});
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<div class="list" tabindex="1"></div>
save your data in localStorage.setItem (return value of .map must save in localstorage)
get your data with localStorage.getItem (get data from localstorage with key that you set for item)
create a template with handlebar.js, and when click on checkbox, render template with data that get from localstorage.
for new data, you must update localstorage.
I have tested the solution from Dipak chavda but it does not work for me also. The problem is that the input is type of hidden. So I changed it to hidden textarea. When you try to copy, I make it visible for a while, focus it, select it's value and then exec the copy. And it works ;)
function copyData(copyText) {
var $txtCopyArea = $("#txtCopyArea");
// set the text as value
$txtCopyArea.val(copyText);
// make textarea visible
$txtCopyArea.removeClass('hidden');
/* focus & select the text field */
$txtCopyArea.focus().select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText);
// hide textarea
$txtCopyArea.addClass('hidden');
}
$('#getthelist').click(function() {
// Clear html div content
$('.list').html("");
var copyText = "";
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
var _data = '<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>';
$('.list').append(_data);
copyText += _data;
});
copyData(copyText);
});
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<textarea id="txtCopyArea" class="hidden"></textarea>
<div class="list"></div>
I tried to give you both questions answer.
Answer of Q1
you should reset HTML content before set new value.
Answer of Q2
you should use document.executeCommand("copy") to copy the text.
Hope it may help to resolve your issue.
function copyData(copyText) {
$("body").append($("<textarea/>").val(copyText).attr({id:"txtareaCopyData"}));
var copyText = document.querySelector("#txtareaCopyData");
copyText.select();
document.execCommand("copy");
$("#txtareaCopyData").remove();
}
$('#getthelist').click(function() {
// Clear html div content
$('.list').html("");
var copyText = "";
$('.inputs>li .color').map(function() {
return {
name: this.closest('[id]').id,
value: $(this).val()
}
}).get().forEach(function(e) {
var _data = '<div>' + '\"' + e.name + '\": \"' + e.value + '\",</div>';
$('.list').append(_data);
copyText += _data;
});
copyData(copyText);
document.querySelector("#txtCopyArea").addEventListener("click", copyData);
});
ul,
li {
list-style: none;
margin: 0;
padding: 0;
}
.list {
margin: 10px;
width: 270px;
padding: 25px;
background-color: #fafafb;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="color_white">
<ul class="inputs">
<input type="radio" value="getthelist" id="getthelist"> Click to get the color values
<li id="color_white">
<div>
<input type="text" value="#fff" class="color">
</div>
</li>
<li id="color_black">
<div>
<input type="text" value="#000" class="color">
</div>
</li>
</ul>
<input type="hidden" id="txtCopyArea" name="txtCopyArea" />
<div class="list"></div>

Selenium and Chrome, having trouble selecting element

I'm using Selenium and Chrome to write a script. I'm having trouble getting Selenium to select and click on two elements. Here's the element I'm trying to select:
HTML of Element 1:
<td class="menuItem" id="tWlans" style=""><a href="frameWlan.html"
id="cWlans" accesskey="W" onmouseover="highlight('Wlans')"
onmouseout="removeHighlight('Wlans')" onclick="selectTab('Wlans')"
onfocus="highlight('Wlans')" onblur="removeHighlight('Wlans')"
target="mainFrame"><u>W</u>LANs</a></td>
HTML of Element 2:
<td class="listNoPad">
<input type="TEXT" name="1.6.7.wlan_id" class="statictextboxlink"
onclick="editThisWlan(this.value,this.name)" readonly="" size="7" value="7">
</td>
I've tried selecting the element by id and by XPath, neither of which works.
function siteNavigate() {
sleep(4500);
driver.findElement(By.xpath('//*[#id="cWlans"]')).click();
//driver.findElement(By.id('cWlans')).click();
}
Thanks in advance for any help and suggestions.
Edit:
function helpAction(pageId, startpage) {
var baseHref = window.location.href;
var index = baseHref.indexOf("/screens");
baseHref = baseHref.substring(0, index);
var href = "/helpfiles/oweb/index.html";
var editWindow = window.open(baseHref + href, "editWindow", "left=100 top=50 menubar=no,toolbar=yes,width=800,height=600,status=yes,resizable=yes");
if (navigator.appName != "Netscape") {
editWindow.location.href = baseHref + href;
editWindow.location.reload(true);
}
editWindow.focus();
}
function feedbackAction() {
var URL = 'http://www.cisco.com/go/wireless-feedback';
var feedbackWindow = window.open(URL, "FeedbackWindow", "left=100 top=50 menubar=no,toolbar=no,scrollbars=yes,titlebar=yes,width=800,height=800,status=yes,resizable=yes");
feedbackWindow.focus();
}
function selectTab(tabName) {
// All this function does is update the value of the hidden field and call the updatePage() function
// Obtain object reference to hidden field
var fieldObj = document.getElementById("hSelectedTab");
// Store the new tab selection in the hidden field
fieldObj.value = tabName;
updatePage();
}
function highlight(tabName) {
//remove highlight for all the tabs
removeHighlightAll();
var highlightObj = document.getElementById("t" + tabName);
// Only highlight if srcElement is a tab object.
highlightObj.style.backgroundColor = "#25546B";
}
function removeHighlight(tabName) {
var highlightObj = document.getElementById("t" + tabName);
highlightObj.style.backgroundColor = "";
}
function removeHighlightAll() {
document.getElementById("tMonitor").style.backgroundColor = "";
document.getElementById("tWlans").style.backgroundColor = "";
document.getElementById("tSwitch").style.backgroundColor = "";
document.getElementById("tWireless").style.backgroundColor = "";
document.getElementById("tSecurity").style.backgroundColor = "";
document.getElementById("tManagement").style.backgroundColor = "";
document.getElementById("tCommands").style.backgroundColor = "";
document.getElementById("tHelp").style.backgroundColor = "";
document.getElementById("tFeedback").style.backgroundColor = "";
}
function updatePage() {
// Clear the current tab selection
removeSelection();
// Obtain object reference to hidden field
var fieldObj = document.getElementById("hSelectedTab");
// Retrieve the selected tab
var selectedTab = fieldObj.value;
// Highlight the selected tab
cellObj = document.getElementById("t" + selectedTab);
cellObj.className = "selected";
}
function removeSelection() {
removeHighlightAll();
// Brute force method to clear the tab selection
document.getElementById("tMonitor").className = "menuItem";
document.getElementById("tWlans").className = "menuItem";
document.getElementById("tSwitch").className = "menuItem";
document.getElementById("tWireless").className = "menuItem";
document.getElementById("tSecurity").className = "menuItem";
document.getElementById("tManagement").className = "menuItem";
document.getElementById("tCommands").className = "menuItem";
document.getElementById("tHelp").className = "menuItem";
document.getElementById("tFeedback").className = "menuItem";
}
function DisplayMsgIfAny() {
if (document.forms[0].err_flag.value == 1) {
alert(document.forms[0].err_msg.value);
} else if (document.forms[0].result_flag.value == 1) {
alert(document.forms[0].cmd_result.value);
}
document.forms[0].err_flag.value = 0;
document.forms[0].result_flag.value = 0;
document.forms[0].buttonClicked.value = 0;
}
//need to get image for the OEMS and change the logo image.
function getLogoImage() {}
A {
TEXT-DECORATION: none
}
#home_icon {
height: 12px;
}
A:link {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A:hover {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A:active {
COLOR: #000000;
TEXT-DECORATION: none
}
A:visited {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A.command {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A.command:hover {
COLOR: #ff9100;
TEXT-DECORATION: underline
}
P {
FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
TD {
FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
P {
FONT-SIZE: 11px;
MARGIN: 0px;
COLOR: #333366
}
TD {
FONT-SIZE: 12px
}
TD.menuItem {
PADDING-RIGHT: 10px;
PADDING-LEFT: 10px;
PADDING-BOTTOM: 4px;
PADDING-TOP: 5px;
BORDER-BOTTOM: #000000 5px solid;
width: 1%;
white-space: nowrap;
}
TD.selected {
PADDING-RIGHT: 10px;
PADDING-LEFT: 10px;
PADDING-BOTTOM: 4px;
COLOR: #000000;
PADDING-TOP: 5px;
BORDER-BOTTOM: #ff9100 5px solid;
width: 1%;
white-space: nowrap;
}
TD.space {
WIDTH: 50%;
}
.style2 {
COLOR: #ffffff
}
<script language="JavaScript" src="../servicescript41.js"></script>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="updatePage(); DisplayMsgIfAny();">
<table width="100%" height="53" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="PADDING-BOTTOM: 4px" align="middle" background="../images/background_web41.jpg" width="180">
<img src="../images/cisco/cisco-logo-2007.gif" width="67" height="40" alt="logo" />
</td>
<td valign="bottom" background="../images/background_web41.jpg">
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td class="menuItem" id="tMonitor" style=""><u>M</u>ONITOR</td>
<td class="selected" id="tWlans" style=""><u>W</u>LANs</td>
<td class="menuItem" id="tSwitch" style=""><u>C</u>ONTROLLER</td>
<td class="menuItem" id="tWireless" style="">W<u>I</u>RELESS</td>
<td class="menuItem" id="tSecurity" style=""><u>S</u>ECURITY</td>
<td class="menuItem" id="tManagement" style="">M<u>A</u>NAGEMENT</td>
<td class="menuItem" id="tCommands" style="">C<u>O</u>MMANDS</td>
<td class="menuItem" id="tHelp">HE<u>L</u>P</td>
<td class="menuItem" id="tFeedback" style=""><u>F</u>EEDBACK</td>
<td class="space"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<div style="position:absolute; right:0px; top:0px; margin: 3px 10px 0px 0px">
<p>Sa<u>v</u>e Configuration | <u>P</u>ing | <a class="command" href="#" accesskey="g" onclick="javascript:logoutAction();">Lo<u>g</u>out</a> | <u>R</u>efresh</p>
</div>
<form method="post" action="/screens/banner.html">
<input type="hidden" name="access_control" size="16" maxlength="15" value="1">
<input name="hSelectedTab" type="hidden" id="hSelectedTab" value="Wlans">
<input type="hidden" name="err_flag" size="16" maxlength="15" value="0">
<input type="hidden" name="err_msg" size="512" maxlength="511" value="">
<input type="hidden" name="result_flag" size="16" maxlength="15" value="0">
<input type="hidden" name="cmd_result" size="512" maxlength="511" value="Config Saved">
<input type="hidden" name="ping_address" size="50" maxlength="50" value="">
<input type="hidden" name="interfaceType" size="11" maxlength="11" value="">
<input type="hidden" name="buttonClicked" size="16" maxlength="15" value="0">
</form>
</body>
Edit 2:
Error message from Node.js:
NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="cWlans"]"}
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
at WebDriverError (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:27:5)
at NoSuchElementError (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:192:5)
at Object.checkLegacyResponse (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:546:15)
at parseHttpResponse (C:\Selenium\node_modules\selenium-webdriver\lib\http.js:509:13)
at doSend.then.response (C:\Selenium\node_modules\selenium-webdriver\lib\http.js:441:30)
at process._tickCallback (internal/process/next_tick.js:109:7)
From: Task: WebDriver.findElement(By(css selector, *[id="cWlans"]))
at thenableWebDriverProxy.schedule (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:807:17)
at thenableWebDriverProxy.findElement (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:1014:17)
at siteNavigate (C:\Selenium\byot.js:29:8)
at sleep.then (C:\Selenium\byot.js:21:5)
From: Task: WebElement.click()
at thenableWebDriverProxy.schedule (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:807:17)
at WebElementPromise.schedule_ (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:2010:25)
at WebElementPromise.click (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:2092:17)
at siteNavigate (C:\Selenium\byot.js:29:37)
at sleep.then (C:\Selenium\byot.js:21:5)
Ok, I apologize in advance. I didn't realize initially that the page had several iframes nested inside the page. To make a very long story short, the frames ended up being the problem the whole time. The site was set up with four frames, some of which changed depending on context and some that essentially stayed static after the initial login. The hardest part was knowing which frame to switch to, and keeping track of which context I was currently focused in on.
Here's what I ended up with:
const {Builder, By, until} = require('selenium-webdriver');
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.get('http://sitetonavigate.com');
driver.manage().window().maximize();
driver.findElement(By.name('bSubmit ')).click();
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// Wait until Chrome is fully loaded to launch AutoIT login script
sleep(4500).then(() => {
autoIT();
});
function autoIT() {
var child_process = require('child_process');
var workerProcess = child_process.execFile("C:\\Selenium\\autoITscript.exe");
sleep(2500).then(() => {
siteNavigate();
});
}
function siteNavigate() {
driver.switchTo().frame("banner");
driver.findElement(By.id('cWlans')).click();
//Select correct WLAN
sleep(2500).then(() => {
driver.switchTo().defaultContent();
driver.switchTo().frame("mainFrame");
driver.switchTo().frame("content");
driver.findElement(By.xpath('/html/body/form/table[3]/tbody/tr[8]/td[2]/input')).click();
});
}
You can use:
Element1 :
driver.findElement(By.id('tWlans')).click();
Element2 :
driver.findElement(By.name('1.6.7.wlan_id')).click();
You are clicking on the TD because it has the ID, tWlans. You (presumably) want to click on the A tag contained within. I would suggest the CSS selector, #tWlans > a. The code is below. I added a wait but it may or may not be needed.
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#tWlans > a"))).click();
As for the second element, it wasn't in your full HTML posted so I'm not sure if it's unique but you can try these couple CSS selectors:
input[name='1.6.7.wlan_id']
input[onlick^='editThisWlan']

How to dynamically create table in html with certain constraints?

i want to take input from user(number) and display image as many times as number.If user inputs 5 then the image should be displayed 5 times next to each other with corresponding number below the images-Below 1st image '1' 2nd Image '2'.Basically putting this table in loop.
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<IMG SRC="C:/Users/User/Desktop/RE/G.JPG">
</TD>
</TR>
<TR><TD ALIGN="CENTER">1</TD>
</TABLE>"
</BODY>
</HTML>
You can use jQuery for this task and write a function that generates HTML with a dynamic value:
Complete Solution
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function generateTable(number) {
return "<table><tr><td>" +
"<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
number +
"</td></table>";
}
$(function(){
var userInput = 3;
for (var i = 0; i < userInput; i++) {
$('#dynamic').append(generateTable(i + 1));
}
});
</script>
</head>
<body>
<div id='dynamic'></div>
</body>
</html>
You can add an input and a button to trigger the function.
You could also check if the inserted value is actually a number or not.
$(document).on('click', '#add', function() {
var that = $(this);
var times = parseInt($('#times').val());
for (i=1;i<=times;i++) {
$('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
}
});
$(document).on('input', '#times', function() {
var that = $(this);
var value = that.val();
if ((value != '' || value != false) && !isNaN(value)) {
$('#add').prop('disabled', false);
} else {
$('#add').prop('disabled', true);
}
});
#table-wrp {
height: 80px;
}
.table-times {
width: 100px;
height: 80px;
float: left;
border-collapse: collapse;
}
.table-times td {
border: 1px solid #d8d8d8;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>
Or for a pure javascript version of Pugazh's answer
var tab = "<div></div>";
var num = prompt("Enter a number");
for(i = 0; i < num; i++){
document.getElementById('tab').innerHTML += "<div><div><img src='http://placehold.it/150x150'></div><div></div></div>";
}
img{
float: left;
box-shadow: 5px 5px 10px rgba(0,0,0,0.4);
height: 100px;
width: 100px;
margin: 10px;
}
<div id="tab"></div>
This will work just as well, but doesn't require jQuery as well.
<HTML>
<BODY>
<div id="tbl"></div>
</BODY>
</HTML>
<script>
var num = prompt("Enter a number");
var div=document.getElementById("tbl");
var l1='',l2="";
for(i=0;i<num;i++)
{
l1 += '<td><img src="C:/Users/User/Desktop/RE/G.JPG"></td>';
l2 += '<td>'+i+'</td>';
}
div.innerHTML = "<table><tr>"+l1+"</tr><tr>" + l2 + "</tr></table>";
</script>
Try this
$(function() {
var tab = "<div></div>";
var num = prompt("Enter a number");
for (i = 0; i < num; i++) {
$("#tab").append("<div class='left'><div><img src='http://placehold.it/150x150'></div><div>" + (i + 1) + "</div></div>");
}
});
div.left {
display: inline-block;
margin-right: 5px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tab">
</div>
</body>
</html>

Categories

Resources