I've been trying to solve this problem for about a week now with no luck. I'm trying to save a value from a form field to a cookie onclick="updatePricingFunction() but when I click the updatePricingFunction button attached to the onclick, the value doesn't change to the new number. Can anyone help me with this?
function updatePricingFunction(){
var beforeNoonField = document.getElementById("beforeNoonNPSlot"); // beforeNoonNPSlot is a form id.
document.cookie = "beforeNoonCookie=" + beforeNoonField; // Create the cookie
}
lol your code was a bit wrong, but say for argument's sake, you had
<form name="myform">
Enter Number<input type="text" name="sampletext" id="beforeNoonNPSlot">
<button type="button" onclick="updatePricingFunction()">Set Cookie</button>
</form>
you need to get the name of your form and the name of the texbox where you want to get the value from. So that when the button is clicked the function updatePricingFunction() will be called, it will retrive the value from The textbox in your form
function updatePricingFunction()
{
//To get a value in a text field, you must have your variable equals
//document.forms["(form name here)"]["(name of the text field here)"].value
var beforeNoonField = document.forms["myform"]["sampletext"].value;//This gets your value
document.cookie = "beforeNoonCookie=" + beforeNoonField; // Create the cookie
}
Take note that this method is a more conventional method of getting values with javascript so you should be using this more often.
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 am trying to make it so my textbox input saves after being changed even after page refresh. I successfully made it to work but discovered a few problems.
All my other input textbox now also have the same new stored value once I change one.
This is because I had put the id element of all my textbox inputs for this section of my website the same. I just discovered that this is bad so I am trying to find a fix.
However, if I change all the ids uniquely, how do I make them all store their own modified user inputs without having to re-write the same function code for each id textbox?
Here is my code so far:
Event handling:
//store value after changes
function store(){
var nb = this.value;
localStorage.setItem("qty",nb);
}
//local storage to keep values after refresh
function getValue(){
var storeNb = localStorage.getItem("qty");
if(storedText != null){
document.getElementById("qty").value = storedNb;
}
else
document.getElementById("qty").value = 0;
}
Event registering:
document.getElementById("qty").oninput = store; //stores new values to localstorage upon changes
document.getElementById("qty").onload = getValue(); //gets value from localstorage upon page load
HTML (all the inputs are like thus, one per webpage):
<input type="text" id="qty" name="qty" class="small">
I have a text field that should be filled before custom saving through HTML custom button.
When a user fills this field and tries to save through custom button, the text inside this field is null even if the user fills it.
Any suggestions Please?
Many Thanks for replying to my query. Actually, I am calling the below function from custom HTML button and I saw the result from alert message as NULL value until I leave the text box. Once I click some other Field then I am getting right value and saving the record successfully. I have posted my code below please have a look and suggest me how I can achieve it. So how to get the text value if a user doesn't leave the text box and click on the Save button?
function createRecord() {
var oDescription = Xrm.Page.getAttribute("new_description").getValue();
if (oDescription != null) {
var callentity = {};
var activityId;
var currentUserId = Xrm.Page.context.getUserId();
var oLeadId = Xrm.Page.getAttribute("new_lead").getValue()[0].id;
callentity.Subject = "Call Activity";
callentity.Description = oDescription ;
XrmSvcToolkit.createRecord({....Some more functions here...
})
}
HTML Button code for calling above function
<input id="SaveCall" onclick="parent.createRecord()" type="button" value="Save Phonecall"></p>
Xrm.Page.getAttribute(arg).getValue(val) won't return a value until focus is lost from the arg attribute (as you've found out).
Some options you could try:
document.getElementById('new_description_i')[0].value
Removing focus from "new_description" on click of your button.
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 have written a set of javascript functions that allow me to validate user input on a form. I only want to accept valid input, and impose the following behaviour:
When a user enters an invalid form, I display an alert and inform them that the value entered is incorrect. Crucially, the original (valid) value in the form is not changed.
The value is only changed when the value has been validated.
For example, suppose I want to accept only positive integers in a field.
This is the sequence of events that describes the desired behaviour.
Scenario 1 (valid input)
Form loads with valid default in the input field
User types in valid number
Input field value is updated (as per normal form behaviour)
Scenario 2 (INvalid input)
Form loads with valid default in the input field
User types in INvalid number
Alert box is shown alert('Invalid value')
Input field value is NOT CHANGED (i.e. the value is the same as BEFORE the user typed in the invalid number)
[Edit]
The only problem I am facing at the moment (i.e. what this question is seeking an answer for), is Scenario 2, action point 4. More specifically put, the question degenerates to the following question:
How do I stop the value of a field from changing, if I (somehow) determine that the value being entered by the user is invalid. This is really, all I'm trying to answer.
I am also doing server side checks, this question is just about the front end - i.e. refusing to change a field (form text input) value if I determine that the value is incorrect.
BTW, I am using jQuery, and would like to implement this in a manner that separates behaviour from display (I think this is what is meant by the term 'unobtrusive' ?)
Any suggestions on how to implement this behaviour as described above, would be very much appreciated.
PS: I dont want to use yet another jQuery plugin for this. I should be able to use jQuery + the simple javascript validation functions I have already written.
When loading the page, couldn't you create a hidden form value or js variable in which you store the initial/default value for the field? When they change the form field, validate it, and if it passes, update the hidden field or js variable to match that in the field they updated.
When the input given by the user fails validation, show the invalid entry along with the error message and then update the form field back to the value you have saved which would be either the
default value or the last valid value that they entered.
EDIT:
Note that this is only a quick and (very) dirty example of doing what I explained in my answer above. If you have a lot of inputs, you will probably want to store the values in an associative array instead of in hidden form values, but this should give you a good handle on what I am suggesting. I would also strongly encourage you to NOT use alert boxes for notification of invalid answers.
<html>
<head>
<script type="text/javascript">
function validate()
{
var field1 = document.getElementById("field1");
var saved = document.getElementById("field1_save");
if (field1.value < 0 || field1.value > 10)
{
alert("Field1 value of " + field1.value + " is invalid");
// Change the value back to the previous valid answer
field1.value = saved.value;
return false;
}
// Save the valid input
saved.value = field1.value;
return true;
}
</script>
</head>
<body>
Test User Input
<form name="form1" id="form1" method="post">
<input name="field1" id="field1" type="text" value="2" onblur="validate();"/>
<input name="field1_save" id="field1_save" type="hidden" value="2" />
<input name="btnSubmit" type="submit" value="Submit" />
</form>
</body>
</html>