I am not sure whether its logical to get.
Here is the html code for my input box.
<input type="text" id="name" #name="ngForm" [ngFormControl]="userProfileForm.controls['name']"
[(ngModel)]="loggedUserInfo.name" (change)="firechange($event,'name')"
/>
and here is my firechange function
firechange($event, field){
if(this.userProfileForm.controls[field].valid){
this._userService.updateUserProfile(this.loggedUserInfo);
this._userService.loadUserData();
}
}
I want to pass only the event in the firechange function and inside the fire change function I want to get the input field name from the event so that I can understand that which input field in my form triggered the event. Expected code will be something like that
[ngFormControl]="userProfileForm.controls['name']"
[(ngModel)]="loggedUserInfo.name" (change)="firechange($event)"
/>
firechange($event){
if(this.userProfileForm.controls[$event.fieldname].valid){
this._userService.updateUserProfile(this.loggedUserInfo);
this._userService.loadUserData();
}
}
My ideal requirement is, in a form there are number of form fields, I don't even want to write firechange function in each individual form field. Is there any generic way to call the event on each input field value change for a particular form without writing it on each input field?
To get the actual name of the element you can do the following:
firechange(event){
var name = event.target.attributes.getNamedItem('ng-reflect-name').value;
console.log('name')
}
If the id is the same as the name you are passing you can get the name like
firechange(event){
if(this.userProfileForm.controls[$event.target.id].valid){
}
If you want to get hold of the element from within your fire change function you may want to try something like:
firechange(event){
let theElement = event.target;
// now theElement holds the html element which you can query for name, value and so on
}
If you in addition you want to instruct your component to apply the firechange() logic on all of your input fields with one single instruction in your component (and not having to specify this on every single input field) than I suggest you to look at in Angular2 how to know when ANY form input field lost focus.
I hope this helps
If id is not the same or it can change, here's more leverage...
You may want to reflect the [name] property the the element's attribute:
... #input [name]="item.name" [attr.name]="item.name" (change)="fn(input)" ...
Then,
...
fn(input) {
log(input.name); // now it returns the name
}
...
See more here
Try this:
<input type="text" (change)="firechange($event.target.value)">
This worked for me in Angular 10
$event.source.name
Related
I need to copy the value from the input field to the clipboard. Instead of getting the value of the input field I get null.
Here is my Code:
<input type="text" value=${model.anchor_url} id=${properties.anchor_name}>
<button class="c-button" onclick="myFunction()">
<span class="c-button__label">Copy</span>
</button>
<div data-sly-test="${model.anchor_url}">
<p>URL from Model :</p>
<pre>${model.anchor_url}</pre>
</div>
function myFunction() {
const field = document.getElementById(`${properties.anchor_name}`);
navigator.clipboard.writeText(field);
alert("Copied the text to clipboard: " + field);
}
The value for field variable results null even though the id exist and it has a value.
You get an Object with this line: document.getElementById(${properties.anchor_name}). With the parameter value you will get the value from the input field.
So you have to try:
const field = document.getElementById(`${properties.anchor_name}`).value;
You are trying to copy the element, instead of it's Value, you have to get it's Value using element.value, also if the value of field variable is null, this means the Element you are trying to get doesn't exist with that Element ID
And also, you were trying to copy the whole element instead of it's value, So Replace the first line in your function with this one:
const field = document.getElementById(properties.anchor_name).value;
Also there is no need to put template literals in your code as you can do so without that too!
For example assume there is a variable element_ID which can be written in JS like this:
var element_ID = "myInput"
now i want to get that Element, so I can just directly do this:
document.getElementById(element_ID)
instead of this:
document.getElementById(`${element_ID}`)
Thanks for all the help. It appears due to cross site scripting prevention JS can not be executed from html for the site I develop but has to be built using TypeScript.
I have an input element and a button in React:
<li><input type="text" placeholder="Enter new ID"></input>
<button onClick={(e)=>this.saveKonfigElementHandler()}>Save</button></li>
Now, when I enter some value into the input field, I want to save the value into some array when I click on the button.
Is it somehow possible to get a reference to that input field (e.g. the target.value of the input field) to save it when clicking the button?
Or would I simply have to do it with an onChange event that saves the current input value into some Variable, and when I click the button, I will simply retrieve that value to save it into some array? Maybe that would be a lot simpler.
E.g:
<input type="text" value={this.state.inputFieldText.join('')} onChange={(event) => this.textHandler(event)}></input>
in the textHandler Method, I will save the target value from the input field into a Class Component state variable in the textHandler() method. And when I click the button, I retrieve that state value and can do some manipulation with it?
A modern way to do it, with function components, hooks and a controlled form element, is:
import { useState } from 'react'
function MyComponent({ initialId, onSave }) {
const [newId, setNewId] = useState(initialId)
return (
<li>
<input
type="text"
placeholder="Enter new ID"
onChange={(e) => setNewId(e.target.value)}
/>
<button onClick={() => onSave(newId)}>Save</button>
</li>
)
}
I'd also note that it is considered better accessibility practice to use a label element for describing the purpose of your field, rather than a placeholder. Placeholders are more appropriate for example input.
Is it somehow possible to get a reference to that input field (e.g. the target.value of the input field) to save it when clicking the button?
Yes.
Or would I simply have to do it with an onChange event that saves the current input value into some Variable, and when I click the button, I will simply retrieve that value to save it into some array? Maybe that would be a lot simpler.
That would be a slightly more React way to do it.
Your DOM-only approach is more "uncontrolled" (see these docs for what controlled/uncontrolled means). You'd do it like this:
Change your onClick to pass e to the handler:
onClick={(e)=>this.saveKonfigElementHandler(e)}
In saveKonfigElementHandler, use e.target.previousElementSibling to access the input:
saveKonfigElementHandler(e) {
const { value } = e.target.previousElementSibling;
// Use `value` ...
}
That's fragile, of course; if you change your structure so another element is between the button and the input, or the input is within a container element, etc., it'll break — which is one argument for the controlled approach. You could store a link to the input in a data attribute on the button:
<li><input id="id-input" type="text" placeholder="Enter new ID"/>
<button data-input="#id-input" onClick={(e)=>this.saveKonfigElementHandler(e)}>Save</button></li>
and then use querySelector to get it:
saveKonfigElementHandler(e) {
const { value } = document.querySelector(e.target.getAttribute("data-input"));
// Use `value` ...
}
but the you're having to keep selectors unique, etc.
Which you choose, controlled or uncontrolled, is ultimately up to you.
I'm not sure about your question. Do you want something like this ?
<button data-input="#id-input" onClick={this.saveKonfigElementHandler(value)}>Save</button></li>
saveKonfigElementHandler = (value) => (event) => {}
I know it's simple and there's probably something wrong with my syntax but I just don't understated it. I'm talking about the following:
//declaration of a string
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
str_input = $('input[name=po]').val();
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
That's it, can you help me to sort it out? The problem so far is that str_input is undefined regardless of what is written in the input, though, it saves its initial value.
Your html tag is invalid:
<input type"text" name = 'po' id="po" value="asd">
Should be:
<input type="text" name = 'po' id="po" value="asd">
// ^ Missing this character (=)
Ok, Now I understood, you can do 2 things, first, you can create a button than when the user clicks it calls the function to store the value in the variable like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$("#MyButton").click(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
<input type="button" id="MyButton" value="Click Here" />
Or the blur function when the user lose focus of the input text like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$('input[name=po]').blur(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
Ok, so here is the solution, though it's a little bit in "from Alf to Alf" style. So, yes, the code I've posted in the main post uses correctly the 'by default' value of the input but the problem comes from that nothing is checking for further changes in the input text field. I'm using $(document).ready... which as far as I know runs during the web project is opened and of course enables the use of some jquery methods within it. There is an interesting function called .change() which actually put the whole thing up for me. Take a glance at the following:
$(document).ready(function(){
$('input[type="text"]').change(function(){
str_input = $('input[name=polynom]').val();;
});
str_input = $('input[name=polynom]').val();
});
The second, third and fourth line make the magic actually, where the code in the .change() method updates str_input on each time a change have appeared in the input box field, whereas the str_input = $('input[name=polynom]').val(); outside of change() takes into account the initial value of the input. That's it... I knew I was forgetting something and yeah...
P.S. Another approach is to use a function and a button (a.k.a. an event-triggered function) which to 'update' the str_input on event. For this way check the post bellow this one.
I'm working on a dynamic form where you can add or delete fields, Here you can find the fiddle
The first button you find is Add Metric. From this the code generates:
Input Field Metric
Button Add Tag
Inside this field a user can add a tag with the button Add Tag, generated when you click add Metric. When you click Add Tag button, two fields are generated:
Input Field Id
Input Field Value
The Html code that I need to generate in order to serialize the entire form (this is not however the question point) will result like this:
<input type="text" name="metrics[0][name]" value="Text 0"> // Metric
<input type="text" id="TagId0" name=" "> //Tag Id
<input type="text" id="TagValue" name="metrics[0][tags][][0]">
Problem:
I need that (when I fill the field with id="TagId0") the value I select will go immediately to the field name with id="TagValue". This field must result like this:
Consider I write on TagId0 the word "hello", field will become:
<input type="text" id="TagValue" name="metrics[0][tags][hello][0]">
How, if it's possible, it can be done?
Thanks
You can use the change method to detect a change in the fields value. Then use the attr method to change the name. Hope I understood correctly. Here is the modified JSFIDDLE.
$(document).on('change', '#InputsWrapper .inputID', function(){
thisVal = $(this).val();
thisName = $(this).siblings('.inputVal').attr('name');
newName = thisName.replace('[tags][', '[tags][' + thisVal);
$(this).siblings('.inputVal').attr('name', newName);
});
Don't forget to press enter after change the field value :)
Edit: I also added two classes to the fields you are appending. .inputID and .inputVal. I hope this helps!
you can write id of field something like TagId-0 and some common class like tagfield,so that u can split the value to get the index an then access it using the class
$(".tagfield").keypress(function() {
var id=parseInt($(this).attr("id").split("-"));
$(this).siblings().attr("name","metrics["+id+"][tags]["+$(this).val()+"][0]");
});
I have a function like this, the product id will be passed by an argument called productID. product_id is a hidden field in which the value will be stored. I have two fields which uses the same function. I want to specify the function from which field the value is coming from so it can update particular hidden field.
function transferId(productID)
{
document.getElementById("product_id").value =productID;
}
The above function is from toke-input autocomplete where we set up the value of the selected option in a hidden field.
In the above function, product_id is the id of the hidden field.
<input type="text" id="product_name" name="product_name" /> //field where the product is selected by autocomplete
<input type="hidden" id="product_id" name="product_id" /> // It stores the value product_id of the product selected.
It works fine when I have one autocomplete text box per form, but now I have two auto complete text boxes. I need the id of the value being passed into the transferId function, so i can write an if condition to update the particular hidden field.
To be more simple, I want to take the ID of the value passed into the function.
Use the below code
function transferId(productID)
{
document.getElementById("product_id").value = productID.id;
}
say for example i click a link:
delete
this link calls transferId(this). the this in the onclick is the link itself. anything related to that link can be accessed via the this. since we passed this, the link itself is passed to this script, aliased as el:
function transferId(el){
alert(el.id); // should give you "link_id"
alert(el.href); // should give you "#"
}
from here, we get the id of the link using el.id as well as other attributes.
in short, just pass this from the event.