I have a text input box where a user inputs what data-* they want to look for in the DOM. I get this user input on a button click then do a little bit of parsing. How would I get the value of the entered text to be the final part of the HTMLElement.dataset selector?
//HTML for text input
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<p id="a"></p>
//JavaScript
var specificSelector = document.getElementById("specificSelector").value;
var a = document.getElementById("a"); // Test element
var parsedSelector = specificSelector.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
//I need to pass the value of the parsedSelector to the below line
var aData = a.dataset.parsedSelector;
console.log("aData: ", aData);
I have read this from MDN Developers but can't figure it out. It looks like you have to pass the data attribute in camel case but might not be able to do it via a variable?
Thanks in advance.
When you need to access an object property via a variable, you need to use array-bracket syntax.
In the example below, type "data-test" into the text box and then hit TAB.
// Get a reference to the input
var specificSelector = document.getElementById("specificSelector");
var a = document.getElementById("a"); // Test element
// Set up an event handler for when the data is changed and the
// input loses focus
specificSelector.addEventListener("change", function(){
// Extract the custom name portion of the data- attribute
var parsedSelector = specificSelector.value.match(/data-(.*)/)[1];
console.log("Parsed selector: ", parsedSelector);
// Pass the string (stored in the variable) into the dataset object
// of another element to look up the object key.
var aData = a.dataset[parsedSelector];
console.log("aData: ", aData);
});
<div class="form-group">
<label for="specificSelector">Specific Selector</label>
<input type="text" class="form-control" id="specificSelector" placeholder="Enter the specific selector here">
</div>
<div id="a" data-test="test2"></div>
Related
This is a simple example to help with a larger project -
Desired outcome: When you type a name in the form box, a sentence appears with the name included. However, only the name should have the color red, and only in the result (it shouldn't be red when it appears in the form box).
I get an error when I include "nameHere.style.color" in this code:
JS:
function getResponse(){
var nameHere = document.getElementById("name").value;
nameHere.style.color = "red";
var resultValue = "Hello my name is " + nameHere + ", nice to meet you.";
document.getElementById("result").innerHTML = resultValue;
}
HTML:
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onchange="getResponse()"></input>
</div>
<div id="result"></div>
Is there any real way to do what I'm trying to do within JavaScript?
Edit: to emphasize, I really do want to change the color of the variable that takes the element.value - not just the element. And I want it to appear in the result as the color. I can't find anything that allows me to do this correctly.
Basically, you apply styles to elements, not raw text. In your code, you are trying to set the style property of a piece of raw text, which doesn't have a style property and therefore is erroring out. In this case, you need to add an element to distinguish your output name. From there, you can either have a class ready (I called this one .theName) and apply the class name to the element or you can just set the style directly (like you were attempting) through script. I show both examples here. The second one uses a setTimeout - which is only to allow a brief delay before changing the color - that is just for illustrative purposes.
function getResponse(){
let nameHere = document.getElementById("name").value;
let resultValue = `Hello my name is <span class='theName'>${nameHere}</span>, nice to meet you.`;
document.getElementById("result").innerHTML = resultValue;
// or if you want to change the element after it's been written to the page
setTimeout(() => {
document.querySelector('.theName').style.color='blue';
}, 1000);
}
.theName{
color:red;
}
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onchange="getResponse()"></input>
</div>
<div id="result"></div>
Sure, you just need to use an element like span instead of a literal string.
const input = document.getElementById("name");
const result = document.getElementById("result");
function getResponse() {
const name = input.value;
let nameWrapper = document.createElement('span');
nameWrapper.style.color = 'red';
nameWrapper.innerText = name;
result.innerHTML = '';
result.appendChild(document.createTextNode('Hello my name is '));
result.appendChild(nameWrapper);
result.appendChild(document.createTextNode(', nice to meet you.'));
}
<div class="formclass">
<label for="name">Input name here</label>
<input id="name" onchange="getResponse()">
</div>
<div id="result"></div>
So the problem is this:
I try to get the text that is inside a specific paragraph with a specific id name and pass it inside a contact form .
i tried this
var src = document.getElementById("ptext"),
dest = document.getElementById("inform");
src.addEventListener('input', function() {
dest.value = src.value;
}};
Where "ptext" is the id of the element with the text of the paragraph and the "inform" is the id of the field in contact form.
The above code will trigger when the user clicks a button.
I am new in Javascript so the code above is probably wrong or faulty.
UPDATE: The HTML Code is this :
<p id="pext">Hello this is the text that is to be imported inside the form field</p>
form field:
<input type="text" name="your-subject" value="" size="40" id="inform" aria-required="true" aria-invalid="false" placeholder="Subjext">
I'm not sure if this is what you were trying to do, but if you're trying to get the text of a paragraph into a form field on a button click (useful a lot of the time with hidden form fields), then here is a code snippet to help you:
var src = document.getElementById("ptext");
var dest = document.getElementById("inform");
var getText = function () {
dest.value = src.innerText;
event.preventDefault();
return false;
}
<p id="ptext">This is some fake text that we'll put into the form.</p>
<form onsubmit="getText()">
<label for="text">Info from paragraph:</label><br>
<input type="text" id="inform" name="text"><br><br>
<input type="submit" >
</form>
Hello and welcome to Stack Overflow :)
To get the text that is inside specific paragraph, use
var src = document.getElementById("ptext").innerText;
To assign the value to an input field (which is what I'm assuming you are trying to do), use
document.getElementById("inform").value = src;
If you supply us with HTML element we could be even more precise.
I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.
I want the value of last textbox to be grabbed by the varialble on multiple textbox with same ID.
HTML
<input type="text" id="get"><br>
<input type="text" id="get"><br>
<button id="grab">Click</button><br>
SCRIPT
$("#grab").click(function(){
var value = $("#get").val();
});
Or, a way to delete the first textbox might also work. Working Example
Your HTML is invalid: HTML elements can't have the same id attribute.
Use the class attribute, instead.
You can then use .last() to get the last element that matches the .get selector:
$("#grab").click(function(){
var value = $(".get").last().val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="get" value="foo"><br>
<input type="text" class="get" value="bar"><br>
<button id="grab">Click</button><br>
(I added the value attributes for demonstrative purposes. Obviously, they can be removed.)
If you want to get the first element's value if the second one is empty, you could do this:
$("#grab").click(function(){
var firstValue = $(".get").val(); // `.val()` gets the first element's value by default
var secondValue = $(".get").last().val();
var result = secondValue || firstValue;
alert(result);
});
If you don't have any control on ids you should use following solution. If you can change the ids you should change them.
You approach will not work because the id is not unique. It will always get the first input.
$("#grab").click(function() {
// var value = $(this).prev("input").val(); // Will work when there is no `<br>`
alert($('input[id="get"]').last().val());
});
Here $('input[id="get"]') will get all the elements having id get and last() will get the last element from it.
Demo: https://jsfiddle.net/orghoLzg/1/
I'd like to save the newly entered values, so I could reuse them. However, when I try to do the following, it does not work:
// el is a textbox on which .change() was triggered
$(el).attr("value", $(el).val());
When the line executes, no errors are generated, yet Firebug doesn't show that the value attribute of el has changed. I tried the following as well, but no luck:
$(el).val($(el).val());
The reason I'm trying to do this is to preserve the values in the text boxes when I append new content to a container using jTemplates. The old content is saved in a variable and then prepended to the container. However, all the values that were entered into the text boxes get lost
var des_cntr = $("#pnlDesignations");
old = des_cntr.html();
des_cntr.setTemplate( $("#tplDesignations").html() );
des_cntr.processTemplate({
Code: code,
Value: val,
DivisionCode: div,
Amount: 0.00
});
des_cntr.prepend(old);
This is the template:
<div id="pnlDesignations">
<script type="text/html" id="tplDesignations">
<div>
<label>{$T.Value} $</label>
<input type="text" value="{$T.Amount}" />
<button>Remove</button>
<input type="hidden" name="code" value="{$T.Code}" />
<input type="hidden" name="div" value="{$T.DivisionCode}" />
</div>
</script>
</div>
You want to save the previous value and use in the next change event?
This example uses .data to save the previous value. See on jsFiddle.
$("input").change(function(){
var $this = $(this);
var prev = $this.data("prev"); // first time is undefined
alert("Prev: " + prev + "\nNow: " + $this.val());
$this.data("prev", $this.val()); // save current value
});
jQuery .data
If you want old/Initial text box value, you can use single line code as follows.
var current_amount_initial_value = $("#form_id").find("input[type='text']id*='current_amount']").prop("defaultValue");
If you want current value in the text box, you can use following code
$("#form_id").find("input[type='text']id*='current_amount']").val();