Override <input type="file"> value property - javascript

It's possible to override value property in tag? My code in JavaScript
var element = document.createElement('input');
element.type = 'FILE';
element.__defineGetter__('value',function(){ return 'ololo'; });
alert(element.value);
It show empty string. Also I try override 'value' with prototype
function BPFILEINPUT(value)
{
this.value = value;
}
BPFILEINPUT.prototype = element;
var myFileInput = new BPFILEINPUT('ololo');
alert(myFileInput.value);
It work, but crash on
form.appendChild(myFileInput);
I try pass test for upload form on 4shared.com
var uplElems = aUploadForm.elements;
for (var i = 0; i < uplElems.length; i++) {
var currentUploadElement = uplElems[i]
if (currentUploadElement.type == 'file') {
if (currentUploadElement.value == '') {
// skip
} else {
if (!checkFileLength(currentUploadElement)) {
return false;
}
filesToUpload += getNumberOfSelectedFiles(currentUploadElement);
}
}
}
if (filesToUpload < 1) {
alert('You didn\'t select any file to upload yet.');
return false;
}
UPDATE
I use UIWebView.

AFAIK, you can't set the value of <input type="file"> programmatically because of security reasons. A user has to explicitly click on it to set its value.

Related

Input number auto change value by stepUp and stepDown

I have this input type="number"
</div>
<input id="data-filter" class="form-control form-control" type="number" value="2021"/>
</div>
What i need is a script that change the input value using the stepUp and stepDown buttons from "2021" to "2022" and then "2021" again. This because i have a function related to that input and the function doesn't read the default value of element input. It happens only if i fill the input text with "2021" again, or i use the stepUp/stepDown buttons.
Edit:
I use that input to perform a search in a table-rows, what i need on the page load is to filter only the rows that contains the year 2021. The function works great, but it doesn't on page load using a default value. So i need to change manualty the input value.
the filter:
$('#data-filter').on('load', function () {
changeFilter.call(this, 'data');
});
the function changeFilter:
function changeFilter(filterName) {
filters[filterName] = this.value;
updateFilters();
}
update filters function:
function updateFilters() {
$('.task-list-row').hide().filter(function () {
var
dataValue = $(this),
result = true;
Object.keys(filters).forEach(function (filter) {
if (filters[filter] && (filters[filter] != 'Tutti') && !filters[filter].includes('-')) {
result = result && dataValue.data(filter).toLowerCase().includes(filters[filter].toLowerCase())
}
else if (filters[filter] && (filters[filter] != 'Tutti') && filters[filter].includes('-')) {
result = result && convertDate(filters[filter]) === dataValue.data(filter);
}
if (filters[filter] === '') {
result = true;
}
});
return result;
}).show();
}
function setUp() {
let dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = ++dataValue;
}
function setDown() {
let dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = --dataValue;
}
function setUp()
{
dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = ++dataValue;
}
function setDown()
{
dataValue = document.getElementById('data-filter').value;
document.getElementById('data-filter').value = --dataValue;
}

Validating different types of form inputs with criterias

I want to get the answers to a form upon submission and parse them to JSON.
This works quite good but I want some validation before sending the data.
I tried a lot of variations of the snippet down below but am still stuck.
Steps:
Prevent default event on "send"
Get Form
Iterate through the elements of the form
Eliminate empty items and their value
If checkbox is checked: value = true
Store correct items in data
Return data
Somehow I can't get to work steps 4 and 5 work at the same time, every time I get one of them to work I screw over the other one.
In this snippet, the checkbox works as intented but the textfield doesn't:
If anybody can point me in the right direction with the if/else statements or something like that it would be greatly appreciated.
document.addEventListener('DOMContentLoaded', function(){
var data = {};
var formToJSON = function formToJSON(form) {
var data = {};
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value =="") {
continue;
}
else {
if (item.checked == false) {
data[item.name] = false;
}
else {
data[item.name] = item.value;
}
}
}
return data; };
var dataContainer = document.getElementsByClassName('results__display')[0];
form = document.getElementById('formular').querySelectorAll('input,select,textarea');
butt = document.getElementById('knopfabsenden');
butt.addEventListener('click', function (event) {
event.preventDefault();
handleFormSubmit(form = form);
});
var handleFormSubmit = function handleFormSubmit(event) {
var data = formToJSON(form);
dataContainer.textContent = JSON.stringify(data, null, " ");
}
}, false);
<div id="formular">
<label class="formular__label" for="machineName">Textfield Test</label>
<input class="formular__input formular__input--text" id="machineNumber" name="machineNumber" type="text"/>
<br>
<input class="formular__input formular__input--checkbox" id="checkTest" name="checkTest" type="checkbox" value="true"/>
<label class="formular__label formular__label--checkbox" for="checkTest">Checkbox Test</label>
<br>
<button class="formular__button" id="knopfabsenden" type="submit">Submit</button>
</div>
<div class="results">
<h2 class="results__heading">Form Data</h2>
<pre class="results__display-wrapper"><code class="results__display"></code></pre>
</div>
The problem is .checked will always be false if it doesn't exist. So the text field gets the value false.
for (var i = 0; i < form.length; i++) {
var item = form[i];
//looking for checkbox
if (item.value ==="") {
continue;
}
else {
if (item.type === "text") {
data[item.name] = item.value;
}
else if (item.type === "checkbox"){
data[item.name] = item.checked;
}
}
}
In this code snippet I check the type of the input and handle it accordingly. also notice I use the === operator and not the == operator as a best practice (Difference between == and === in JavaScript)

Set the value of a Javascript input hidden field to that of a value entered in another input text field

I have an input text field (name: qtyText) to which a user enters a value. I would like to set this value as the value for another hidden field (name: qtyTextHidden) using JavaScript. How can I go about it?
HTML
<input name = "qtyText" type = "textbox" size = "2" value = "" />
<input type="hidden" value = "" name="qtyTextHidden"/>
My efforts to set the field value using JS work, but I am unable to send the value to the servlet. So I am attempting to directly set the value using a function and then try and send it to the servlet. I would like to have a value = someJSFunction() kind. The function needs to trigger upon "onChange" in the "qtyText" input field.
Using jQuery:
$(document).ready(function() {
$('input:text[name="qtyText"]').keyup(function() {
$('input:hidden[name="qtyTextHidden"]').val( $(this).val() );
});
});
Using JavaScript:
window.onload = function() {
if(document.readyState == 'complete') {
document.getElementsByTagName('input')[0].onkeyup = function() {
document.getElementsByTagName('input')[1].value = this.value;
};
}
}:
I'd suggest:
function updateHidden(valueFrom, valueTo) {
valueTo.value = valueFrom.value;
}
var inputs = document.getElementsByTagName('input'),
textInputs = [],
hiddenInputs = [],
refersTo;
for (var i = 0, len = inputs.length; i < len; i++) {
switch (inputs[i].type) {
case 'hidden':
hiddenInputs.push(inputs[i]);
break;
case 'text':
default:
textInputs.push(inputs[i]);
break;
}
}
for (var i = 0, len = textInputs.length; i < len; i++) {
refersTo = document.getElementsByName(textInputs[i].name + 'Hidden')[0];
if (refersTo !== null) {
textInputs[i].onchange = function () {
updateHidden(this, document.getElementsByName(this.name + 'Hidden')[0]);
};
}
}
JS Fiddle demo.
Incidentally: there is no type="textbox". At all. Ever. Anywhere in HTML, not even in HTML 5: it's type="text". The only reason it works with type="textbox" is because browsers are ridiculously forgiving and, if the type isn't understood, it defaults to type="text".
To set the value of the hidden field the easiest way is to use the javascript function that to pass three parameters from, to, and form names:
<script type="text/javascript">
function someJSFunction(form, from, to){
var el_from=form[from], el_to=form[to];
el_to.value=el_from.value;
return el_to.value;
}
</script>
<form name="myform">
<input name = "qtyText" type = "textbox" size = "2" value = "" onchange="someJSFunction(myform, 'qtyText', 'qtyTextHidden')"/>
<input type="hidden" value = "" name="qtyTextHidden"/>

More efficient way of writing this javascript

I am creating a contact form for my website and and using javascript to the first layer of validation before submitting it which is then checked again via php but i am relatively new to javascript, here is my script...
$("#send").click(function() {
var fullname = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
if (fullname == ""){
$("input#fullname").css("background","#d02624");
$("input#fullname").css("color","#121212");
}else{
$("input#fullname").css("background","#121212");
$("input#fullname").css("color","#5c5c5c");
}
if (email == ""){
$("input#email").css("background","#d02624");
$("input#email").css("color","#121212");
}else{
$("input#email").css("background","#121212");
$("input#email").css("color","#5c5c5c");
}
if (subject == ""){
$("input#subject").css("background","#d02624");
$("input#subject").css("color","#121212");
}else{
$("input#subject").css("background","#121212");
$("input#subject").css("color","#5c5c5c");
}
if (message == ""){
$("textarea#message").css("background","#d02624");
$("textarea#message").css("color","#121212");
}else{
$("textarea#message").css("background","#121212");
$("textarea#message").css("color","#5c5c5c");
}
if (name && email && subject && message != ""){
alert("YAY");
}
});
How can i write this more efficiently and make the alert show if all the fields are filled out, thanks.
$("#send").click(function() {
var failed = false;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
var item = $(this);
if (item.val()) {
item.css("background","#121212").css("color","#5c5c5c");
} else {
item.css("background","#d02624").css("color","#121212");
failed = true;
}
});
if (failed){
alert("YAY");
}
});
glavic and matt's answers were exactly what I was going to suggest, except I would take it a step further by separating the logic from the presentation.
Have classes defined in your css for when a field contains an invalid entry, and add or remove that class using $.addClass() or $.removeClass()
Since you're using jQuery, I would recommend setting a class on each field that requires a non-blank value (class="required").
Then you do something like this:
var foundEmpty = false;
$(".required").each(function()
{
if($(this).val())
{
foundEmpty=true;
$(this).style("background-color", "red");
}
});
if(foundEmpty)
{
alert("One or more fields require a value.");
}
Giving them a common class, define classes to apply the styles, and do this:
JS
$("#send").click(function() {
$('.validate').attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( $('.invalid').length === 0 ) {
alert('YAY');
}
});
CSS
.valid {
background:#121212;
color:#5c5c5c
}
.invalid {
background:#d02624;
color:#121212;
}
HTML
<button id="send">SEND</button><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate"><br>
<input class="validate">
JSFIDDLE DEMO
A little bit more efficient approach:
var validate = $('.validate');
$("#send").click(function() {
validate.attr("class", function() {
return $(this).val() === "" ? "validate invalid" : "validate valid";
});
if( validate.filter('.invalid').length === 0 ) {
alert('YAY');
}
});
You can use jQuery to iterate over each object and get their values. Depending on your form, this code will change, but it's to give you an example. I'm probably missing a couple of brackets here and there but the concept is there.
var objectName=$(this).attr('id');
$('#formId').children().each(
function(){
if ($(this).value == ""){
$(this).css("background","#d02624");
$(this).css("color","#121212");
$error[objectName]='true';
}else{
$(this).css("background","#121212");
$(this).css("color","#5c5c5c");
$error[objectName]='false';
}
}
);
$.each(error, function(key, value){
if (value=='false'){
alert (key + 'is empty');
}
});
I would probably divide part of this up into my css file. If any of the fields are empty add a class like "empty" to the object, if not, remove it. Then in your css file you can add some descriptors like:
input#fullname,
input#email {
...
}
input#fullname.empty,
input#email.empty {
...
}
You can use jQuery addClass() and removeClass().
You can then add a loop as follows:
var inputs = new Array();
inputs[0] = "input#fullname";
inputs[1] = "input#email";
inputs[2] = "input#subject";
inputs[3] = "textarea#message";
var complete = true;
for (var i = 0; i < 4; i++) {
var value = $(inputs[0]).val();
if (value.length > 0) {
$(inputs[i]).removeClass("empty");
} else {
complete = false;
$(inputs[i]).addClass("empty");
}
}
if (complete) {
}
EDIT:
There you go, fixed it for you.

Javascript - verify the values of fields with dynamic names

I have a set of text fields qty with dynamic names: like qty541 ; qty542 ; qty957
formed by the word: "qty" and the product id
How can I verify if all my qty fields are empty or not with Javascript ?
Thanks a lot.
The easiest way is to use a javascript framework like JQuery, Protoype, etc. With this framework you can create a search pattern in reg expr manner. If you unable to use one, it does need more work:
One way:
var formObj = document.forms[0]; //as an example
var fields = formObj.getElementsByTagName("input");
for (i=0; i < fields.length, i++)
{
if (fiedls[i].name.indexOf("qty") > 1)
{
//do something
}
}
You can loop through the elements of the form:
var form = document.getElementById('theForm');
var index;
var field;
for (index = 0; index < form.elements.length; ++index) {
field = form.elements[index];
if (field.name.substring(0, 3) === "qty") {
// Check field.value here
}
}
Live example
The above assumes the form has an id, but however you get access to the form element, the rest follows.
Off-topic: A lot of this stuff is made much simpler by the utility functions available in various JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others. They also smooth over browser differences (or outright browser bugs), allowing you to focus on the job in hand rather than worrying about browser inconsistencies.
Using:
<p>
<input type="text" name="qty3232" value="43"/><br/>
<input type="text" name="qty5532" value="as"/><br/>
<input type="text" name="qty5521" value=""/><br/>
<input type="text" name="qty3526" value="34"/>
</p>
<br/>
<h3>Log</h3>
<pre id="log"></pre>
Javascript (no jQuery):
var inputs = document.getElementsByTagName('input');
var log = document.getElementById('log');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'text' && inputs[i].name.substring(0,3) == 'qty') {
if (inputs[i].value == '') {
log.innerHTML += inputs[i].name + " value empty.\n";
} else {
log.innerHTML += inputs[i].name + " value not empty.\n";
}
}
}
http://jsfiddle.net/jxmMW/
This is much easier using a selector in jQuery, though.
var log = $('#log');
$('input[name^="qty"]').each(function(){
if (this.value == '') {
log[0].innerHTML += this.name + " value empty.\n";
} else {
log[0].innerHTML += this.name + " value not empty.\n";
}
});
http://jsfiddle.net/jxmMW/1/
Plain JS:
For example use class="quantity" on all fields and use getElementsByClassName - which almost takes us into jQuery mode
window.onbeforeunload=function() {
var elems = document.getElementsByClassName("quantity"); // needs help in some browsers
for (var i=0,n=elems.length;i<n;i++) {
if (elems[i].value!="") {
return "You have filled in a quantity");
}
}
}
window.onload=function() {
document.forms[0].onsubmit=validate;
}
function validate() {
var elems = document.getElementsByClassName("quantity");
for (var i=0,n=elems.length;i<n;i++) {
if (elems[i].value=="") {
alert("Please fill in a quantity");
elems[i].focus();
return false;
}
}
}
standard method:
function validate() {
var elem;
for (var i=0,n=this.elements.length;i<n;i++) {
elem = this.elements[i];
if (elem.name && elem.name.indexOf("qty")===0) {
if (elem.value=="") {
alert("Please fill in a quantity");
elem.focus();
return false;
}
}
}
return true; // allow submit
}

Categories

Resources