javascript: Syntax to capture both string value of element name and element - javascript

I am getting hung up on how to go back and forth between the string value of the id of an element and element itself. I believe the problem involves syntax but cannot get it right. I would like to pass one parameter in javascript (in this case "title" and use it as a string and an element as follows to make a title disappear and an edit title box appear.
html
//note this html is actually written to page by another javascript function
<span id="title">Title</span><span id="titleedit"></span><img src="edit.gif" onclick="editTitle('title');">
If I leave out apostrophes around title I can get it to work as an element in following but then it does not work as a string.
javascript
function editTitle(field) {
//using field as string only works if parameter in above is in apostrophes
var fieldedit = field+"edit"
var editstring = '<input type="text" name="title" onclick="saveTitle();">save';
document.getElementById('fieldedit').innerHTML = "editstring";
//using as element only works if above has no apostrophes
field.style.display="none";
}
Thanks for suggesting how to accomplish both tasks...make title disappear and titleedit appear passing just word title. (The reason I want to pass title as parameter as there are a whole bunch of other fields to edit that I'd like to pass as one parameter each.)

When you say document.getElementById('fieldedit'), you're saying "the element with "fieldedit" as the id". What you want is "The element with the contents of the variable fieldedit as the id.
Give it a shot with document.getElementById(fieldedit).innerHTML = editstring;.
Update:
There is also a problem with this line:
var editstring = "<input type="text" name="title" onclick="saveTitle();">save";
Try escaping your quotes, or using a mixture of single and double quotes. For example:
var editstring = '<input type="text" name="title" onclick="saveTitle();">save';
Update 2:
To obtain a reference to the element with id="title":
var field = document.getElementById('title');
Now that field refers to that element, you can use:
field.style.display = 'none';
You can also do it all in one line:
document.getElementById('title').style.display = 'none';

document.getElementById('fieldedit').innerHTML = "editstring";
Shouldn't that be
document.getElementById(fieldedit).innerHTML = editstring; ?
You want to get the span with the id "titleedit" and insert the input element stored in editstring, if I understand your question.

Related

How to find a varible html element executing javascript in python

I'm trying to use 2Captcha service to solve an h captcha V2.
Works like this:
you get a value to solve the captcha
Then you find a textarea element in the HTML code to insert that value (here's my problem)
you insert the value in that element
You press submit button and the captcha is solved
First I'm going to present a working example, then I'll present where I have the problem.
This is the HTML code to find and insert the obtained value:
textarea id="h-captcha-response" name="h-captcha-response" style="display: none;"></textarea>
This is the python code used to insert the value:
value = get_value()
insert_solution = 'document.getElementById("h-captcha-response").innerHTML="' + value + '";'
driver.execute_script(insert_solution)
What this exactly does is taking you from this:
and this is the result:
Finally you press the submit button and it's done. This example works
This is my problem:
In my case the HTML document has a variable ID, like this one:
<textarea id="h-captcha-response-0tesbrpxsk8" name="h-captcha-response" style="display: none;"></textarea>
Notice that the id has an alphanumerical part (0tesbrpxsk8) that always changes making it more difficult to select.
I tried to find some regular expression to use inside of document.getElementById()
With no success
I also tried to use:
document.getElementByTagName("textarea").innerHTML=".....
I'm stucked here and tried other approaches with no success because I probably because I don't implement well those solutions or they just don't work.
I'll appreciate some insights, thanks
This will fill out all of those (recaptcha / hcaptcha):
driver.execute_script('''
let [captcha] = arguments
[...document.querySelectorAll('[name="h-captcha-response"],[name="g-recaptcha-response"]')].map(el => {
el.innerHTML = captcha
})
''', value)
Try this:
const textarea = document.querySelector('[id^="h-captcha-response-"]')
textarea.value = "This is inside the textarea!"
<textarea id="h-captcha-response-0tesbrpxsk8" name="h-captcha-response"></textarea>
First of all: You set the value of an textarea with textarea.value = "some value"
You should use document.querySelector() to select elements. (You have much more abilities there)
You can select id starting with, with this query: [id^="start"]

Using Javascript to write HTML inputs which call Javascript functions

I'll give you an example of what I'm trying to do.
In Javascript:
document.innerHTML += "<input type='button' id='moveButton' value='a' onclick='webInput('a');'>"
The problem is that the html being written has two levels of quotes, and I can't figure out how to format the second level of quotes here:
webInput('a')
In my Javascript file, I have one function write the inputs into the HTML at the end of the function, then clicking the inputs calls the next function, until eventually the inputs are rewritten.
I know the answer probably has something to do with Escape Characters, but I was confused as to how to format them because the text is being passed back and forther between Javascript and HTML, which use different Escape Characters.
You can create your button within the javascript code and define the method therein.
var button = document.createElement('button');
button.addEventListener('click',function(){
doSomething();
});
//This method adds your button to body
document.body.appendChild(button)
If you have requirements to add this as string to the document, you need to escape quotes:
"<input type='button' id='moveButton' value='a' onclick='webInput(\"a\")'>"
great answer with rules for escaping here: https://stackoverflow.com/a/16134942/5727598
Also, you should use innerHtml property for element in which you want to pass your string but be sure it will remove all content there;
If no requirements, create button and upend to the body:
var input = document.createElement('input');
input.type = 'button';
input.id = 'moveButton';
input.value = 'a';
button.addEventListener('click', function(){
webInput(this.value); //if you need to pass input value as parameter
})
document.body.appendChild(input);

Extract value from html select tag using JavaScript

I am getting whole select tag as a value from my code, in order to do work around the value i need to extract the value from my select tag,as this tag is dynamically created by the code.
Below is the value i am getting. How can i extract this using java script.Thanks for your help.
rowId[0].QValue = "<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>"
The proper way to do this would be to select the element from the DOM with one of the selection functions. In this case, I prefer document.querySelector:
var type112 = document.querySelector('#type112');
The # means 'id', and you can pass any combination of valid CSS to document.querySelector.
Then, to produce the value of this element, simply call
type112.value
This will give you the text value of the currently selected option within the select element.
Based on your comment, I'm sensing that perhaps you have the text of an element and want to parse out the id? If that's the case, you can try:
var elemString = // whatever your str is
var id = (elemString.match(/id="([^"]+)"/) || [])[0];
This assumes that the id is the first attribute in the string, as well as a whole litany of other things that will probably break in production but will work in the absence of a coherent understanding of what you're trying to do.
You can simply use the select element id to retrieve the value of the element.
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>
You can write the javascript to get the element by id Type112
and so on to get the value:
var s = document.getElementById("Type112");
var selNum = s.options[s.selectedIndex].value;
alert(selNum);
Here's a jsfiddle example
Try this.
var list = document.getElementById("Type112");
console.log(list.value)
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>

How to dynamically access user-entered Input-field-data, in Javascript or J-Query

HELP!!.... I can't dynamically access data entered by users into Input fields!
I'm a curriculum-designer trying to make a 'Matching'-activity (18-questions-with-18-scrambled-up-possible-answers), in which answer-choices get dynamically crossed out, 1 by 1, as they get 'used up' by the student, whenever (s)he types the letter of that choice (in this case "r") into the input-field. Here's the HTML for 1 of those 18 matches: (Hint: Pay attention to the "id"-attributes)
HTML
<input title="Question 18 - type 'R' into this input field"
class="questions" maxlength="1" id="18" onblur="My_Blur_Fx(this);">
</input>
<span class="r_as_selected, choices" id="r"> <!--I use the first class ('r_as_selected') in the J-Query example below, and the 2nd class ('choices') in the Javascript example below.-->
[Choice] R. (**All this span should soon be crossed-out.**)
</span>
I thought I could pull this off with a "change" event. However, neither my Javascript, nor my J-Query seems to be able to do it, because neither one can dynamically access the user's typed-in input (the very stuff that PHP would normally access via GET or POST).
J-Query
My J-Query-attempt to dynamically access this user-entered input...
$("input").change(function(){
$("input"[value="r"])
.add('.r_as_selected')
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'})
});
...failed because, although it could cross out the '#r' answer-choice, yet it would ALSO cross it out whenever they typed in ANYTHING....So the [value='r'] part of the code wasn't able to target JUST the field where someone had typed 'r'.
Javascript
My Javascript-attempt to dynamically access this user-entered input...
<script>
function My_Blur_Fx(x) {
var userInput = document.getElementById(x).value;
var userChoices = document.getElementsByClassName("choices").id;
var i;
for(i = 0; i < 18; i++)
{ if (userChoices[i].attributes[1].value == userInput) {
/*Note: "attributes[1] is my way of accessing the 2nd attribute in the HTML span above, which is 'id="r"'*/
userChoices[i].style.textDecoration = "line-through";};
};
}
</script>
...failed too because an 'Input' is an "Element" whose "Value," is defined by the DOM to be "NULL,"...so line 3 above gives an error. Neither could any of the other potentially-relevant DOM-modifiers, instead of .value (i.e. .innerHTML / .nodeValue / .attributes) access that user-entered value. So it seems that 'Input' elements just can't be accessed dynamically. . . . ( Any suggestions...J-Query, Javascript, or other? )
You can't use an attribute selector to match user input, it only matches the static attributes, not the dynamic values. You can use .filter() to search for an element that matches a selector and has a specific value.
$("input").change(function() {
$("input").filter(function() {
return this.value == 'r';
}).add(".r_as_selected")
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'});
});
You have several problems in MyBlurFx().
document.getElementById(x).value won't work beceause x is the element, not its ID. You should just use x.value.
document.getElementsByClassName("choices").id won't work because getElementsByClassName() returns a NodeList, not a single element, so it doesn't have an id property. But you don't need the ID, just use document.getElementsByClassName("choices"), since the for loop operates on the elements, not IDs.
Maybe there is more than one mistake, but I see that your code $("input"[value="r"]) is same as $(undefined). You must use $('input[value=\'r\']') instead.

Get element from string

I have a large string in a variable that includes a whole bunch of HTML tags.
I want to get the value of a hidden input field within the string and store it in its own var.
<input type="hidden" value="WantThis" />
Can anyone help me out at all?
You can parse the HTML with jQuery to get the value:
var theValue = $(myString).find('input[name=something]').val();
I'm assuming the hidden field has a name. If it doesn't, you'll need to specify input[type=hidden] and find it using its position relative to the rest of the content.
If your string does not already have a root element and the <input> is not nested, you'll probably want to use $('<div>' + myString + '</div>') instead.
Get the hidden input like so:
$(html).find("input[type=hidden]").val()
Create an ID for the hidden input and call it like normal
<input type="hidden" value="WantThis" id="myInput" />
Then call it
var myval = $('#myInput').val();

Categories