jQuery - results of DOM manipulation can't be assigned to a variable? - javascript

Using jQuery, I change the value of an input text field through some process. After the process is done, I need to capture this change and apply it to another process. My problem is that I can't seem to capture this change and assign it to a variable. I know the changes are happening because the DOM is getting updated. Furthermore, this variable assignment works in IE, but not for the other browsers I tested.
Below is a snippet to prove my point (and you can see this online here: http://jsfiddle.net/xMwAE/).
<form>
<input type="hidden" name="my_hidden" value="Hidden Field" />
<input type="text" name="my_text" value="Text Field" />
</form>
$().ready(function() {
$('input[name=my_hidden]').val('Hello Hidden Field');
$('input[name=my_text]').val('Hello Text Field');
// Display
var temp = $('form').html();
// Though the DOM is updated with the new values. The variable temp
// does not capture the changes to the input text field, but captures
// the change in the hidden field. When in IE, temp captures the
// changes in both fields.
alert(temp);
});
Obviously, I need consistent behavior across browsers. Any ideas what's going on?

I don't get any trusted idea what happens, but somehow there should be a difference between setting the value as a member (input.value) or setting the value as a attribute-node.
This works for me :
$('input[name=my_text]').each(function()
{ this.setAttribute('value','Hello Text Field');});
I guess its a bug in innerHTML, see bugzilla: https://bugzilla.mozilla.org/show_bug.cgi?id=535992

Alternatively, you can store the values of your fields into array and use however you like like this:
var data = [];
$('form :input').each(function(){
data.push(this.value);
});
Now you can check for values like this:
alert(data[0]);
alert(data[1]);

Related

How to get an element value that is not showing in html code with Cypress?

this is the code of my element
<input type="text" class="nameOfClass" id="someid" name="somename" maxlength="255" placeholder="justholder" ng-model="model" tooltip-placement="top" tooltip-trigger="mouseenter" tooltip-animation="false" style="">
as you can see there is no attribute value, but I can clearly see that there is text in that text field in web app I am trying to automate.
So my problem is, that I don't know how to get value of the text field.
I've tried google chrome inspector to find where is the value but without any luck. Somewhere I read, that caching can causing this problem, but in the network console I can see the values in request response.
Thanks
Assuming that you want to get the value written in the text field, you can get it by invoking val.
cy.get('#someid')
.invoke('val')
.then((value) => {
cy.log(value) //logs the value
})
If you want to apply any assertion on the value, you can:
cy.get('#someid').should('have.value', 'your-value')
If you are referring to type="text", that's not the text the user types in - it's an attribute that tells the input what values to allow.
You can also have type="number", type="date", type="color", etc
Checking that input is of type "text" would be done with this,
cy.get('input#someid').should('have.attr', 'type', 'text')
Checking the value property would be done like this
cy.get('input#someid')
.type('entering a value') // there's nothing in value yet
.should('have.value', 'entering a value')

How to force dijit/form/TextBox to update the variable bound to it immediately - binding does not work as expected

I have an
<input id="myTextBox" data-dojo-type="dijit/form/TextBox" data-dojo-props="value: at(model, myValue)" />
When I try to copy the value from model.myValue to another input (e.g. by
window.setInterval(
function() { document.getElementById("theOtherInput").value = model.myValue; }, 1000);
I notice, that the value of myTextBox isn't synchronized with model.myValue until the <input> of myTextBox lost focus. I.e. - theOtherInput won't be updated unless I leave the input field myTextBox.
How to force dojo to synchronize the input with the bound variable with every keystroke? I thought that this should have been the default behavior or at least it should be possible with little effort, but I don't find the right attribute to do it. Any ideas?
The main problem for me is, when I submit the form by the enter key, the model.myValue has still the value before the input myTextBox got the focus. (and I don't want a hack with setInterval - I just want to have dojo doing its job of synchronizing the input with the model)
The closest you can get is setting intermediateChanges property to true and attach an onChange event. Something like this:
<input id="myTextBox" data-dojo-type="dijit/form/TextBox"
data-dojo-props="intermediateChanges: true"
data-dojo-attach-event="onChange: _myOnChange"
data-dojo-props="value: at(model, myValue)" />
Now, inside your widget, the _myOnChange function will run with each valuable keystroke or if the content is changed.
_myOnChange: function(newValue){
console.log(newValue);
document.getElementById("theOtherInput").value = newValue;
}

Javascript to "copy in real time" some fields from a form to another form (with different input names)

I'm trying to write a function to copy some fields (in real time) from a specific form, to another form
I try to be more specific:
I have 2 forms
- The first form is the one the user will fill in.
- The other form is hidden.
When the user will fill the first form, the second form (hidden) will be filled by the same informations.
Some fields are automatically filled by some calculations, so I can't use keyup/keypress or "click" to start the function
I wrote something like this, but it doesn't work
$(function(){
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function(){
$('input[name="inputname2"]', form2).val(function(){
return $('input[name="inputname1"]', form1).val();
});
});
});
You can copy in real time using the keyup function, something like this. Otherwise, when you say
Some fields are automatically filled by some calculations
What do you mean? These calculations are made by you using JS or what? Because, if you are using JS you can fill the two fields at the same time when you make the calculations.
this works for me...
$(function() {
$('#i1').change(function(evt) {
$('#i2').val(evt.target.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name1" id="i1" />
</form>
<form>
<input type="text" name="name2" id="i2" />
</form>
The change event is fired after the element has lost the focus. For the "user editable" elements you should use keyup (for the textbox) and change for the drop down elements.
On the other hand, for the fields filled automatically, you don't have any nice and clean solutions. I can think in two options:
If the calculations trigger is always the user changing some value, you could copy every form value after that happens.
(very bad option, but it would still work) You could be constantly checking for changes in every element and copying them using setInterval function.
As a side note
As well as your code should work, there is a simpler way to do it:
$('#fieldname_form1').change(function(){
var value = $('input[name="inputname1"]', form1).val();
$('input[name="inputname2"]', form2).val(value);
});
This should work -
$(function() {
var form1 = $('#form1'),
form2 = $('#form2');
$('#fieldname_form1').change(function() {
$('input[name="inputname2"]', form2).val($(this).val());
});
});

Dynamically adding new fields resets values in previous fields

I using an HTML / Javascript combination to add fields dynamically.
Here is the jsfiddle for it: http://jsfiddle.net/kM9Yg/2/
My problem is, if I input values in a field, and then click on the Add More button, a new field gets added but the previous fields' values get reset.
The button to add more is of type <input type="button"/> and not <input type="reset" />
Any way to prevent this?
Use DOM methods, not innerHTML. DOM methods are standardised, innerHTML is not. Some browsers will reflect the current value as the default value, others will not.
You can do:
var el, oEl = document.getElementById('divToClone');
if (oEl) {
el = oEl.cloneNode(true);
// code here to fix duplicate ids and
// set style.display = '' so it's visible
oEl.parentNode.appendChild(el);
}

JavaScript: True form reset for hidden fields

Unfortunately form.reset() function doesn't reset hidden inputs of the form.
Checked in FF3 and Chromium.
Does any one have an idea how to do the reset for hidden fields as well?
Seems the easiest way of doing that is having <input style="display: none" type="text"/> field instead of <input type="hidden"/> field.
At this case default reset process regularly.
This is correct as per the standard, unfortunately. A bad spec wart IMO. IE provides hidden fields with a resettable defaultValue nonetheless. See this discussion: it's not (alas) going to change in HTML5.
(Luckily, there is rarely any need to reset a form. As a UI feature it's generally frowned upon.)
Since you can't get the original value of the value attribute at all, you would have to duplicate it in another attribute and fetch that. eg.:
<form id="f">
<input type="hidden" name="foo" value="bar" class="value=bar"/>
function resetForm() {
var f= document.getElementById('f');
f.reset();
f.elements.foo.value= Element_getClassValue(f.elements.foo, 'value');
}
function Element_getClassValue(el, classname) {
var prefix= classname+'=';
var classes= el.className.split(/\s+/);
for (var i= classes.length; i-->0;)
if (classes[i].substring(0, prefix.length)===prefix)
return classes[i].substring(prefix.length);
return '';
}
Alternative ways of smuggling that value in might include HTML5 data, another spare attribute like title, an immediately-following <!-- comment --> to read the value from, explicit additional JS information, or extra hidden fields just to hold the default values.
Whatever approach, it would have to clutter up the HTML; it can't be created by script at document ready time because some browsers will have already overridden the field's value with a remembered value (from a reload or back button press) by that time that code executes.
Another answer, in case anyone comes here looking for one.
Serialize the form after the page loads and use those values to reset the hidden fields later:
var serializedForm = $('#myForm').serialize();
Then, to reset the form:
function fullReset(){
$('#myForm').reset(); // resets everything except hidden fields
var formFields = decodeURIComponent(serializedForm).split('&'); //split up the serialized form into variable pairs
//put it into an associative array
var splitFields = new Array();
for(i in formFields){
vals= formFields[i].split('=');
splitFields[vals[0]] = vals[1];
}
$('#myForm').find('input[type=hidden]').each(function(){
this.value = splitFields[this.name];
});
}
You can use jQuery - this will empty hidden fields:
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).val('');
});
Tip: just make sure you're not resetting csrf token field or anything else that shouldn't be emptied. You can narrow down element's specification if needed.
If you want to reset the field to a default value you can use(not tested):
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).each(function() {
var $t = $(this);
$t.val($t.data('defaultvalue'));
});
});
and save the default value in the data-defaultvalue="Something" property.
I found it easier to just set a default value when the document is loaded then trap the reset and reset the hidden puppies back to their original value. For example,
//fix form reset (hidden fields don't get reset - this will fix that pain in the arse issue)
$( document ).ready(function() {
$("#myForm").find("input:hidden").each(function() {
$(this).data("myDefaultValue", $(this).val());
});
$("#myForm").off("reset.myarse");
$("#myForm").on("reset.myarse", function() {
var myDefaultValue = $(this).data("myDefaultValue");
if (myDefaultValue != null) {
$(this).val(myDefaultValue);
}
});
}
Hope this helps someone out :)
$('#form :reset').on('click',function(e)({
e.preventDefault();
e.stopImmediatePropagation();
$("#form input:hidden,#form :text,#form textarea").val('');
});
For select, checkbox, radio, it's better you know (hold) the default values and in that event handler, you set them to their default values.
Create a button and add JavaScript to the onClick event which clears the fields.
That said, I'm curious why you want to reset these fields. Usually, they contain internal data. If I would clear them in my code, the post of the form would fail (for example after the user has entered the new data and tries to submit the form).
[EDIT] I misunderstood your question. If you're worried that someone might tamper with the values in the hidden fields, then there is no way to reset them. For example, you can call reset() on the form but not on a field in the form.
You could think that you could save the values in a JavaScript file and use that to reset the values but when a user can tamper with the hidden fields, he can tamper with the JavaScript as well.
So from a security point of view, if you need to reset hidden fields, then avoid them in the first place and save the information in the session on the server.
How I would do it is put an event listener on the change event of the hidden field. In that listener function you could save the initial value to the DOM element storage (mootools, jquery) and then listen to the reset event of the form to restore the initial values stored in the hidden form field storage.
This will do:
$("#form input:hidden").val('').trigger('change');
You can reset hidden input field value using below line, you just need to change your form id instead of frmForm.
$("#frmForm input:hidden").val(' ');

Categories

Resources