Get custom HTML attribute value from controller - javascript

I have added a custom attribute (cust-property) to a HTML input control,
<input name="myInputName" type="text" ng-model="myModel" cust-property="My Value">
Now I'm trying to get the value of the custom defined attribute from the validation error object list
for (var i in $scope.form.$error.required) {
var elementName = $scope.form.$error.required[i].$name;
//var customPropertyValue = $scope.form.$error.required[i].cust-property;
}
How can I get the custom HTML attribute value from controller?

Try this:
var id = $scope.form.$error.required[i].attributes['cust-property'].value;
But you should also get a try on directive.

Maybe something like this?
HTML:
<input id="myInputName" name="myInputName" type="text" ng-model="myModel" cust-property="My Value" onClick="getCustom()">
JS:
function getCustom() {
var mydiv = document.getElementById('myInputName');
var custom = mydiv.getAttribute("cust-property");
alert(custom);
}

Related

Storing value of a text input in AngularJS

I have an input:
In the controller I want to obtain the value of the text input by setting available. For example:
vm.inputValue = document.getElementById('link').value;
It breaks my code as I get a console error of:
TypeError: Cannot read property 'value' of null
What am I doing wrong?
AngularJS have a directive that does it to you, the ng-model. It binds in a variable the input you enter in the HTML and it reflect the changes you make in the variable inside your controller in JavaScript.
In your HTML
<input type="text" ng-model="vm.myText">
{{ vm.myText }} <!-- This is output the value of vm.myText in the HTML -->
<button ng-click="vm.logData()"></button>
In your JavaScript
function MyController(){
var vm = this;
vm.myText = '';
vm.logData = logData;
function logData(){
console.log('Your data is ', vm.myText);
// This easy, you can access your value in the JavaScript
}
}
Probably you forget to set the id (id = "link")of the input field in HTML:
<input id = "link" type = "text">
Also, you can do the same thing using ng-model
<input ng-model = "vm.inputValue" type = "text">
And from controller, you can get the correct value if you define a scope variable:
$scope.vm = {};
$scope.vm.inputValue = "";

Keyup function into form element

I have a script I am using to copy a field into another input field using keyup blur paste. This script works, however I need to modify it to also go into two different form elements which are named data-cost="" and debt="", instead of the <div id="viewer">
This is the script as I have it now :
$(function () {
$('#account_balance1').on('keyup blur paste', function() {
var self = this;
setTimeout(function() {
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
}, 0);
});
$("#viewer").text($('#Website').val().replace(/^\$/, ''));
});
This is the html :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value=""/>
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" debt="" value="" type="checkbox" name="f_2[]"/>
if you need the two attributes (data-cost and debt) to be each set to your value you need:
$("input[data-cost][debt]").attr('data-cost',str.replace(/^\$/, ''));
$("input[data-cost][debt]").attr('debt',str.replace(/^\$/, ''));
Just use that selector then
$("input[data-cost][data-debt]")
I think you're maybe having a fundamental misunderstanding of what the data attributes are for? You're aware that they will not be posted with the form? I think what you're looking for is the data function which will allow you to set the data attributes http://api.jquery.com/data/.
Perhaps you want data-cost and data-debt?
So if your input looks like this:
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" id="checkboxId" />
Then you can set the values in your javascript like this:
var value1="some value";
var value2="another value";
$('#checkboxId').data('cost', value1);
$('#checkboxId').data('debt', value2);
I don't believe having an attribute named simply "debt" as you have it above is valid.
I'd do it this way (setTimeout was useless) :
$(function () {
$('#account_balance1').on('keyup blur paste', function () {
var self = this;
var nextCheckbox = $(self).next("input[type='checkbox']");
var str = $(self).val();
$("#viewer").text(str.replace(/^\$/, ''));
nextCheckbox.data({
cost: str,
debt: str
});
/*
You won't be able to see changes if you inspect element,
so just check in console
*/
console.log(nextCheckbox.data());
});
});
And your html markup must be slightly modified :
<!--This where I get the value from -->
<input type="text" class="balance" id="account_balance1" name="cardb" value="" />
<!--the first 2 elements are where I need the values to go -->
<input data-cost="" data-debt="" value="" type="checkbox" name="f_2[]" />
<!--I added the viewer to check if everything works properly -->
<div id="viewer"></div>

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

jQuery access input hidden value

How can I access <input type="hidden"> tag's value attribute using jQuery?
You can access hidden fields' values with val(), just like you can do on any other input element:
<input type="hidden" id="foo" name="zyx" value="bar" />
alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());
Those all mean the same thing in this example.
The most efficient way is by ID.
$("#foo").val(); //by id
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
https://developers.google.com/speed/docs/best-practices/rendering?hl=it#UseEfficientCSSSelectors
There's a jQuery selector for that:
// Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );
// Filter those which have a specific type
hidden_fields.attr( 'text' );
Will give you all hidden input fields and filter by those with a specific type="".
To get value, use:
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
var valueOfHidFiled=$(this).val();
alert(valueOfHidFiled);
}
});
or:
var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);
To set value, use:
$('input[type=hidden]').attr('value',newValue);
There is nothing special about <input type="hidden">:
$('input[type="hidden"]').val()
If you want to select an individual hidden field, you can select it through the different selectors of jQuery :
<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/>
$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class
If you have an asp.net HiddenField you need to:
To access HiddenField Value:
$('#<%=HF.ClientID%>').val() // HF = your hiddenfield ID
To set HiddenFieldValue
$('#<%=HF.ClientID%>').val('some value') // HF = your hiddenfield ID
Watch out if you want to retrieve a boolean value from a hidden field!
For example:
<input type="hidden" id="SomeBoolean" value="False"/>
(An input like this will be rendered by ASP MVC if you use #Html.HiddenFor(m => m.SomeBoolean).)
Then the following will return a string 'False', not a JS boolean!
var notABool = $('#SomeBoolean').val();
If you want to use the boolean for some logic, use the following instead:
var aBool = $('#SomeBoolean').val() === 'True';
if (aBool) { /* ...*/ }
Most universal way is to take value by name. It doesn't matter if its input or select form element type.
var value = $('[name="foo"]');

Categories

Resources