How Can I call a dynamic index in function cshtml? - javascript

I have this function :
<script>
function f(id){
return $("#" + id).val();
}
</script>
And this html's tag:
<input id=f(#payMethod) type="radio" value=" #method.Value" name="cartaCont" />
My id is buildered with a foreach that pass value to variable:
string payMethod = "payMethod";
payMethod += method.Text;
My question is: Is correct Call this index in an other function in this way ?? :
function() {
$('input[id ^= #PayMethod]').attr('checked', headerChecked);
}
thanks for feedback

It seems that you want to write some html and javascript code, relating to each item of a list.
In this case, I often prefer to directly write html and related javascript for event binding and code customization.
I supposing that method is your razor variable in your foreach, and methods is the enumerable variable to loop, you may would write this code for html
#foreach(var method in methods)
{
// this is C#, not javascript
// replacing spaces to build right id code for html
string payMethod = "payMethod" + method.Value.Replace(" ", "");
<text>
<input id="#payMethod" class="payMethodRadio" type="radio" value="#method.Value" name="cartaCont" />
<script>
$(document).ready(function () {
$("##payMethod").on('change', function (e) {
/* here if you want to write some javascript events for each item related to its html ID, for example change event */
});
});
</script>
</text>
}
But if you want to write some common jQuery code for this set of radio buttons, I' prefer to manage it with class selector rather than ID rules, as follow
function() {
$('payMethodRadio')...
}
Hope this, help you for better code management.
Br
Andryx

Try to add Onchange event to input.Here is a demo code:
#{var payMethod = 0;}
#foreach (var method in Model.Methods)
{
<input id="#payMethod" type="radio" value=" #method.Value" name="cartaCont" onchange="Add(#payMethod)"/>
payMethod++;
}
js:
function Add(id) {
$('#'+id).attr('checked', headerChecked);
}

Related

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

jquery not able to get value from a hidden field

I am trying to get a value from a hidden field. I am using the code
function foo(){
alert($('#idhere').val());
}
the answer i am getting is only the first word of that sentence.
the value is a large sentence I am using the above code inside a function foo and this function foo is called inside a append function inside a ajax call.
$.each(data, function(i, item) {
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere" value="item[0]"');
}
Why am i getting only a single word as alert.
Am i doing it wrong
Well, where is "#idhere"?
There is no element that has this id assigned!
You have not given id idhere to element.
Try:
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');
i think you miss the id in hidden field
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');
Id should be unique! You use $.each, that means you probably will create many elements with the same id. That's bad.
$.each(data, function(i, item) {
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere' + i + '" value="item[0]"');
}
Use:
function foo(){
alert($('#idhere0').val());
}
Or:
var vals = $.map($('input[type="hidden"]'), function(el) {
return $(el).val();
});
alert(vals.join('\n'));

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources