element.value method is returning undefined - html

I have an ajax 'POST' method that sends the id input to a php file. For some reason whenever I write input.value method, it returns undefined:
input = document.getElementsByClassName("Input");
const id = input.value;
alert(id);
What am I doing wrong?
Edit: I tried making the element as a separate id instead of a class and the problem disappeared.

getElementsByClassName() returns an array-like collection of elements, not a single element.
You'll need to extract one of the elements from the collection, e.g.
input = document.getElementsByClassName("Input");
const id = input[0].value; //<--
alert(id);
Better would be to target the exact element in some way e.g.
document.querySelector('#theActualElement'); //<-- returns single element

Related

.innerText of an element is not showing up

I have a div that is contenteditable and grabbing the div using useRef(), which is a reactjs hook.
When I try to display the text inside the contenteditable div, the alert shows nothing but the log shows the text.
Is there something I am missing?
this is just a snippet I created
export default function Input() {
const inputRef = useRef();
const showText = () => {
console.log("text: ", inputRef.current.innerText);
alert("text: ", inputRef.current.innerText);
}
return (
<>
<div ref={inputRef} contentEditable="true" supressContentEditableWarning={true} />
<button onClick={showText}>Show text</button>
</>
)
}
It also does't work when I use it as a value inside an object eg.
const obj = {
text: inputRef.current.innerText
}
I will be thankful if someone can help me understand what is going on here!!
UPDATE
just don't use alert to debug lol.
Is there anything stopping you from getting the innerText using DOM like this-
var innerText = document.getElementById('elementName').innerText
then passing the value to your reactJS?
window.alert only takes a single parameter, so only the first string is shown. If you pass in too many arguments to a javascript function, the extra parameters will simply be ignored. This is different from console.log, which is a variadic function, meaning it will take any number of parameters and display all of them.
Try alert("text: " + inputRef.current.innerText) instead.

Puppeteer js attempting to get value of data-src in img tag

Currently I have the following HTML:
I'm needing to get the data-src link that is there. My code in puppeteer js is:
await page.waitForSelector('#ldpPhotoGallery');
const getImgSrc = await page.$$eval('#ldpPhotoGallery', imgs => imgs.map(img => {img.getAttribute('data-src')}));
console.log(getImgSrc);
Here I wait for the page id then after it's loaded it should run the page evaluation. I'm not sure if I'm doing this correctly. From what I understand I'm evaluation the id ldpPhotoGallery then from there it returns the contents. From there I'm searchinging getAttribute data-src and it should return it no? The console.log is [null]. I know the data is there. What am I doing wrong?
It seems you just have a typo in the arrow function format: .map(img => {img.getAttribute('data-src')}) would fill all the array with undefined, as an arrow functiond body in curly brackets without retutn implicitly returns undefined. Then undefined is serialized as null and you get [null]. Just remove curly brackets or add explicit retutn.
BTW, you need not page.$$eval() for id selector, it returns an array with just one element. page.$eval() may suffice:
await page.waitForSelector('#ldpPhotoGallery');
const getImgSrc = await page.$eval('#ldpPhotoGallery', img => img.getAttribute('data-src'));
console.log(getImgSrc);

The character of the textarea input is turned to object

for example
in
input name:1111,ss:1111,... => {name:1111,ss:1111,...}
A method of turning characters into objects
I can't find a good way to do it
So, you need this method or what?
if need method, it's simple: just get value of textarea, wrap text into quotes, add braces and call on it JSON.parse()
var textarea = document.getElementById("id-of-textarea");
var value = textarea.value;
var wrapped = "{"+value.replace(/(\w+)/g, '"$1"') + "}";
var result = JSON.parse(wrapped);
But, you should expect any values that user can input, so it's not good idea to use textarea for input some data.
As per the structure of you input I would suggest you to use different textfields to capture data rather than having it into a single textarea. Like this, you will be able to iterate over those and fetch their value and store them in form of an object or a map
Your HTML:
<input id="name" value="1111"/>
<input id="ss" value="2222"/>
...
Your script (JQuery/Javascript):
var data = {};
$('input').each(function () {
data[$(this).attr("id")] = $(this).val();
});

Get data-id from html element

I'm trying to extract the content of data-id.
For example :
<div data-id= "43434"></div>
How can I get the value of 43434? I want to get access to the content of data.
As I see you want to get this value inside a TestCafe test.
If so you can use the Selector.getAttribute() method.
const element = Selector('your-div-selector');
const attrValue = await element.getAttribute('data-id');
// or if you need to use it in an assertion
await t.expect(element.getAttribute('data-id')).eql('43434');
Get the element using has attribute selector and get the value from dataset property or get attribute value using Element#getAttribte method.
console.log(
document.querySelector('div[data-id]').dataset.id
)
<div data-id="43434"></div>

JSON results into a variable and store in hidden input field

I wrote code below that is working perfectly for displaying the results of my sales tax calculation into a span tag. But, I am not understanding how to change the "total" value into a variable that I can work with.
<script type="text/javascript">
function doStateTax(){
var grandtotalX = $('#GRANDtotalprice').val();
var statetaxX = $('#ddl').val();
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
// ...
});
return false;
};
</script>
Currently, $('.total-placeholder').html(data.total); is successfully placing the total number into here:
<span class="total-placeholder"></span>
but how would I make the (data.total) part become a variable? With help figuring this out, I can pass that variable into a hidden input field as a "value" and successfully give a proper total to Authorize.net
I tried this and id didn't work (see the testtotal part to see what I'm trying to accomplish)..
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
// ...
If you are using a hidden field inside a form, you could do:
//inside $.post -> success handler.
$('.total-placeholder').html(data.total);
$('input[name=yourHiddenFieldName]', yourForm).val(data.total);
This will now be submitted along with the usual submit. Or if you want to access the data elsewhere:
var dataValue = $('input[name=yourHiddenFieldName]', yourForm).val();
The "data" object you are calling can be used anywhere within the scope after you have a success call. Like this:
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
var total = data.total;
var tax = data.total * 0.19;
});
return false;
};
Whenever you get an object back always try to see with an alert() or console.log() what it is.
alert(data); // This would return <object> or <undefined> or <a_value> etc.
After that try to delve deeper (when not "undefined").
alert(data.total); // <a_value>?
If you want 'testotal' to be recognized outside the function scope, you need to define it outside the function, and then you can use it somewhere else:
var $testtotal;
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
EDIT:
The comments are becoming too long so i'll try and explain here:
variables defined in javascript cannot be accessed by PHP and vice versa, the only way PHP would know about your javascript variable is if you pass it that variable in an HTTP request (regular or ajax).
So if you want to pass the $testtotal variable to php you need to make an ajax request(or plain old HTTP request) and send the variable to the php script and then use $_GET/$_POST to retrieve it.
Hope that answers your question, if not then please edit your question so it'll be clearer.