How to get the id of a passed arguement in jquery? - javascript

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.

Related

The use of JavaScript onchange("<function>(this.id)") on c# CheckBox vs other c# Controls

I have a web document that has its fields populated dynamically from c# (.aspx.cs).
Many of these fields are TextBox or HtmlTextArea elements, but some are Checkbox elements.
For each of these I have the ID attribute populated on creation of the field, as well as using .Attributes.Add("onchange","markChanged(this.id)")
This works great on all the fields except Checkbox. So I created a markCheckChange as I discovered that the Checkbox won't accept style="backgroundColor:red" or .style.backgroundColor = "red" type arguments.
I also added an alert and found that the Checkbox is not actually passing the this.id into the parameter for markCheckChange(param) function.
As a result I am getting errors of the type:
unable to set property of undefined or null reference
Why and what is the difference between these controls, and is there a better way to handle this?
I just reviewed the inspect element again, and discovered that the Checkbox control is creating more than an input field of the type checkbox, it is also wrapping it in a span tag, and the onchange function is being applied to the span tag (which has no id) and not to the input tag that has the checkbox id. Whereas for TextBox and HtmlTextArea the input tag is put directly within the cell/td tag, no some arbitrary span tag.
So now the question becomes how to get the onchange function to apply to the input tag for the checkbox rather than the span tag encapsulating it?
Per request:
function markChange(param) {
if (userStatus == "readonly") {
document.getElementById("PrintRecButton").style.display = "none";
document.getElementById("PrintPDFButton").style.display = "none";
alert("Please login to make changes.\n\nIf you do not have access and need it,\n contact the administrator");
exit();
}
else {
document.getElementById(param).style.backgroundColor = "teal";
saved = false;
var page = document.getElementById("varCurrentPage").value;
markSaveStatus(page, false);
}
}
So far the markCheckChange is about the same, until I get it to pass the id correctly, I won't be able to figure out the right way to highlight the changed checkboxes.
I found an alternative.
As I mentioned in the edit to the question, the inspect element feature revealed that the CheckBox type control was creating a set of nested elements as follows:
<span onchange="markChange(this.id)">
<input type="checkbox" id="<someValue>">
<label for="<someValue>">
</span>
Thus when the onchange event occurred it happened at the span which has no id and thus no id was benig passed for the document.getElementById() to work.
While searching for why I discovered:
From there I found the following for applying labels to the checkboxes:
https://stackoverflow.com/a/28675013/11035837
So instead of using CheckBox I shall use HtmlInputCheckBox. And I have confirmed that this correctly passes the element ID to the JavaScript function.

how to get input field name through event object in angular 2

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

Binding the same model variable to radio buttons and input-text

I would like manage with AngularJS UI which allows to pick one of the options (displayed as radio buttons group) or a custom value typed in a input-text.
It should look like:
http://jsbin.com/foyujali/7/edit
Here is the code that you can see also in the link below:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<div ng-app="tagsApp" ng-controller="TagsCtrl">
<input type="radio" id="conversion_type_sale" ng-model="tag.conversion_type" value="sale"/>
<label for=conversion_type_sale>Sale</label>
<input type="radio" id="conversion_type_lead" ng-model="tag.conversion_type" value="lead"/>
<label for=conversion_type_lead>Lead</label>
<input type="radio" id="conversion_type_custom" ng-model="tag.conversion_type" value="{{tag.conversion_type_custom_value}}"/>
<input type="text" placeholder="Custom" ng-model="tag.conversion_type_custom_value" id="conversion_type_custom_value"/>
<p>
The choosen conversion type is: <strong>{{tag.conversion_type}}</strong>
</p>
</div>
And JS:
angular.module('tagsApp', []).
controller('TagsCtrl', function ($scope) {
$scope.tag = {conversion_type: 'lead'};
});
I would prefer not to use ngChange directive so I just bind the value or ng-value (I tried both) to the model of the input-text. It doesn't work properly this way, but I suppose there is an elegant AngularJS solution. Any suggestions?
Thanks in advance!
P.S. Just to clarify - I want the following functionality: http://jsbin.com/foyujali/10/edit but I want to avoid using ngChange directive.
This is what you're looking for: http://jsfiddle.net/colares/shcv8e1h/2/
Explaning the behavior
By focusing on the text field, the radio on the left is selected and chosen value is updated regarding the value of the text field;
By focusing on radio on the left of the text field, the chosen value is updated according to what is in the text field as well;
By changing the value of the text field, the chosen value is also updated;
Finally, by focusing on any other label or radio, the custom value remains, while the chosen value is update regarding the selected option.
To do so, I had to use a few more things in custom option input:
ng-focus: when I click on the text field, it updates the chosen value regarding the text field;
ng-change: as I update the text field, the final value is also updated;
ng-model: to store the auxiliar variable customColor, which remains regardless of the selected value.
Remember, the ng-value is used to set the value of the radio (or an <option>) from a given expression when we select it. This makes the radio and input text "bound", because they have the same value.
You could use $scope.$watch and look for the change in your controller like so:
http://jsfiddle.net/2R6aN/
var app = angular.module('tagsApp',[]);
app.controller('TagsCtrl', function ($scope) {
$scope.tag = {conversion_type: 'lead'};
$scope.$watch('conversion_type_custom_value',function(new_val) {
if (new_val) {
$scope.tag.conversion_type = new_val;
}
});
});
$watch is best option. Also, Instead of using modelName in 1st parameter of $watch, you can create your own stuff(eg. watching length of input box) and do desired action on it with second parameter.

jQuery - Change name of an input field by using value of another input field filled at the same time

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]");
});

Search through an HTML Table and find text fields with required classes

I'm creating a validation script for a multi-step form, each group is inside a table and I want to check that the containing table has a required field inside it.
I've tried to implement this as below:
(where a = table id
.required = class, but the classes are like class = "something required")
function validForm(a) {
var myVar = $('a').find('.required').val();
alert(myVar);
}
the problem is that this code returns undefined. This is my first time using a .find function and I am having a hard time understanding how to use it.
HTML:
<table id = "default">
<tr><td>Default</td></tr>
<tr><td>Field name</td><td><input type="text" name="first_name" maxlength="35" class="txtfield-cu1 required" title="First Name"></td></tr> <- repeat a couple of times
if a is the table id, you will need to select by $('#a') instead of $('a').
In jQuery selection (and CSS) '#a' selects the tag with id = 'a', whereas a selects the <a> tag.
Edit: if a here stands for a variable that represents the id of the table, then you can use
$(a) to select it.
Edit 2: jsfiddle link
Try $("#a") to select by ID and not by tag name.

Categories