My markup is written as follows. Pay more attention to the click handler of the uploadBtn button.
<!DOCTYPE html>
<html>
<head>
<title>Cleansing Workbench</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<h1>Cleansing Workbench</h1>
<h3>Upload File</h3>
<form class="form-inline well">
<label class="span3">Enter the file to upload</label><button id="uploadBtn" class="btn btn-default">...</button><label id="filename"></label>
<br />
<label class="span3">Enter Delimiter</label>
<select name="delimiter" id="delimiter">
<option value="comma">Comma</option>
<option value="tab">Tab</option>
<option value="pipe">Pipe</option>
<option value="other">Other</option>
</select>
<label>Specify Delimiter</label>
<input type="text" name="otherDelimiter" id="txtdelimiter" value="Comma (,)" />
<br />
<br />
<div class="text-right">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</form>
<iframe name="upload" id="upload" src="about:blank" style="display:none"></iframe>
</div>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled');
else $this.attr('disabled', 'disabled');
});
};
})(jQuery);
$(function () {
var arrDelimiterEnums = ['Comma (,)',
'Tab Separated ( \\t )',
'Pipe ( | )'];
$txt = $('#txtdelimiter').toggleDisabled();
$('#delimiter').change(function () {
var obj = this;
var indx = obj.selectedIndex;
var val = obj.options[indx].value;
if (val == 'other') {
$txt.val('').toggleDisabled();
}
else {
if (!$txt.attr('disabled'))
$txt.toggleDisabled();
$txt.val(arrDelimiterEnums[indx]);
}
});
$('#upload').load(function () {
});
$('#uploadBtn').click(function () {
var ifr = document.getElementById('upload');
var doc = ifr.contentWindow.document;
if (doc.getElementById('uploader') == null) {
var frm = document.createElement('form');
frm.action = "fileupload.ashx";
frm.method = "post";
frm.id = 'uploader';
var inp = document.createElement('input');
inp.type = "file";
inp.name = 'uploadFile';
inp.id = 'uploadbtn';
var i = $(inp).click(function () {
console.log('hello');
console.log(this.value);
});
frm.appendChild(inp);
doc.body.appendChild(frm);
//i.trigger('click', null);
}
else {
var btn = doc.getElementById('uploadbtn');
$(btn).trigger('click', null);
}
});
});
</script>
</body>
</html>
As soon as the following line executes, the url in my browser gets appended with ?delimiter=comma.
doc.body.appendChild(frm);
I expected this would not reload. So what do I do to not make it reload?
Take your inputs out of the form <form class="form-inline well"> & just manipulate them with jQuery or vanilla javascript.
When buttons are in a form they automatically "submit"/refresh the page.
Related
I am novice in jQuery but trying to learn something very basic. I am just trying to build up auto increment/decrement input fields like this:
<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button class="bottone piu">+</button>
<button class="bottone meno">-</button>
</div>
<script>
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>
Why if i put the div inside a form it doesn't work?
EDIT Thank you very much
Buttons are submit type by default. So when you put it inside the form and click on button your form gets submitted. Changing the type will solve your problem like this
<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>
<script>
$(document).ready(function() {
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>
The form submites because buttons are `type="submit" by default and submit the form. So set the type to button so they do not submit
<button type="button" ..>
Buttons are by default submit here is a working version:
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>
I am trying to create add/remove form fields dynamically with jQuery where the user can submit multiple queries based on the dropdown selections. At the end, it should generate URL with a combination of selection.So far I have managed to create add/remove form fields with the option of multiple queries.
For example, if the user submits input for a car then it will generate URL like:
exmaple.com/?car=xxx
and which is working.
If a user submits input for car and bike then it should generate:
exmaple.com/?car=xxx&bike=yyy
but it is generating like:
exmaple.com/?car=xxx&car=yyy
So how can I solve this issue? Thank you in advance.
$(function() {
$.fn.addmore = function(options) {
var moreElement = this,
singlePreSelectedValue = '',
selectedValue = [],
defaultOption = {
addText: 'add more',
removeText: 'Remote',
selectBoxDuplicate: true,
avoidDuplicationSelection: function(e) {
var o = e;
if ($.inArray($(o).val(), selectedValue) != -1) {
$(o).val(singlePreSelectedValue);
alert('Value already selected.');
} else {
var hasSelectValue = true;
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() == 'select') {
hasSelectValue = false;
return false;
}
});
}
},
prevSelectedValue: function(e) {
var o = e;
selectedValue = [];
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
selectedValue.push($(this).val());
}
});
singlePreSelectedValue = $(o).val();
}
}
defaultOption = $.extend(true, defaultOption, options);
/* $(this).find('select').prepend('<option value="select" selected>Select</option>');*/
$(moreElement).after('' + defaultOption.addText + '');
$('[data-id="more"]').click(function() {
var dataMore = this,
removeDuplication = [];
$(dataMore).before($(moreElement).clone().find('input').not('input[type="submit"]').val('').end().end().find('select.removeDuplication').focus(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.prevSelectedValue(this);
}
}).change(function() {
if (!defaultOption.selectBoxDuplicate) {
defaultOption.avoidDuplicationSelection(this);
}
}).end().append(function() {
return $('<i class="fa fa-trash"></i> ' + +'').click(function() {
$(this).parent().remove();
});
}));
if (!defaultOption.selectBoxDuplicate) {
$.each($('.removeDuplication'), function(i, v) {
if ($(this).val() != 'select') {
removeDuplication.push($(this).val());
}
});
$.each(removeDuplication, function(i, v) {
$('.removeDuplication').last().find('option[value="' + removeDuplication[i] + '"]').remove();
});
}
});
$('.removeDuplication').focus(function(e) {
defaultOption.prevSelectedValue(this);
}).change(function() {
defaultOption.avoidDuplicationSelection(this);
});
return this;
}
$('dl').addmore({
addText: 'Add',
removeText: 'Remove',
selectBoxDuplicate: false
});
});
$(document).ready(function() {
$("select").change(function() {
var str = $(this).val();
$("#searchtermid").attr("name", str);
});
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="navbar-form" action="" method="get" action="demo_form.asp">
<dl>
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</dl>
<input class="btn btn-primary" type="submit" value="Submit">
</form>
After getting input from Standard Quality, I have modified my scripts and html.
https://jsfiddle.net/paul85/wjhqszmg/
But still is not letting the user submit input form. Most important, when user will submit from it should redirect to a page for correctly generated URL.
If user submit input for car and bike then redirecting page address or URL will be:
exmaple.com/?car=xxx&bike=yyy
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="/results.html" method="get">
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication">
<option value="car" >Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>
</div>
</div>
<button class="add_field_button">Add More Fields</button>
<input class ="btn btn-primary" type="submit" value="Submit" >
</form>
JAVASCRIPT
$(document).ready(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication">\
<option value=""></option>\
<option value="car">Car</option>\
<option value="bike">Bike</option>\
<option value="plane">Plane</option>\
</select>\
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).val()+' already selected.');
}
});
});
/*$(form).submit(function(e){*/
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
if (query.type !=""){
queries.push(query);
} else{
slectedall=false;
}
});
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
if (query.value.trim() ===""){
fillupfield=false;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Please insert your searchterm.');
} else {
$("form").submit();
}
}
});
});
It looks like you're extending jQuery, which isn't necessary for this, and is contributing to making the code much less legible. To be honest, I haven't even dug through it to find the problem -- instead, I wrote something from scratch. StackOverflow snippets don't allow forms, so here's a working JSBin: http://jsbin.com/gokodaluna/edit?html,js,output
(Note that I've changed your HTML markup a little bit)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="" method="get" action="demo_form.asp">
<div class="fields">
<div class="form-field">
<select class="removeDuplication">
<option value="car">Car</option>
<option value="bike">Bike</option>
<option value="plane">Plane</option>
</select>
<textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<h2 id="final-url"></h2>
</body>
</html>
Javascript:
/* Save your initial variables */
var form = $('#main-form');
var formFields = form.find('.fields')
var addButton = $('#form-add');
var emptyInput = $('.form-field').clone(); // clone this at initialization so we always have an empty field
var finalUrl = $("#final-url");
addButton.on('click', function() {
emptyInput.clone().appendTo(formFields);
/* clone this again so our initial field is always empty and available */
})
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
query.value = $(field).find('textarea').val();
queries.push(query);
});
var url = window.location.href;
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
url += ampOrQ + query.type + "=" + query.value;
}
/* print the URL into the dom if you want to see it working */
finalUrl.text(url);
/* or forward users to the new URL you've generated */
window.location.href = url;
})
Edit: in the revised code in your question, you're calling $("form").submit() in that if-else statement. When you trigger this, the larger function is still catching the submit event, so it's immediately running e.preventDefault() again. If you need to simply forward the user to the new URL, just set it with window.location.href =. See the last few lines of my (edited) code above.
I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?
<html>
<head>
<title>sum totals</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
$('input[name="selectedItems1"]').click(function(){
var j = document.getElementById("output");
if (this.checked) {
j.value=j.value+300
}else{
j.value=j.value-300
}
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Place the <script> tag after <form>
Reason:
When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.
Try this :
<html>
<head>
<title>sum totals</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script type="text/javascript">
function calculate(){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var tons = $('#tons').val();
if ( rege.test(tons) ) {
val = parseInt(tons);
var treesSaved = val * 17;
if($('input[name="selectedItems1"]').is(":checked"))
{
treesSaved = treesSaved +300;
}
else
{
treesSaved = treesSaved -300;
}
if(isNaN(treesSaved))
j.value=0
else
j.value=treesSaved;
}
else
alert("Error in input");
}
$(function(){
$('input[name="selectedItems1"]').change(function(){
calculate();
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Some elements of the different scripts are working but I cannot seem to get the saved comments to appear at the bottom of the page. Any suggestions as why some parts aren't working? When someone writes there name and in the text box and I press clear it clears the said fields, but I cannot get the comments saved and then displayed on the page. What have I done wrong?
<!DOCTYPE html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-
8" />
<title>Matthew comments</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="myScript.js"></script>
<script>
function clearComment(){
$('#txt1').val('');
};
</script>
<script>
function saveComment()
var ctext = $('#txt1').val()
var cname = $('#namebox').val()
if (cname === 'Name'){cname = 'Anon';
alert(‘saveComment cname=’+cname+’ ctext=’+ctext)
};
</script>
<script>
var cmtlist = ‘<p><span class=”cmtname”’+cname+
</span>'+ctext+’</p>’;
$(‘#cmtlist’).empty();
$(‘#cmtlist’).append(cmtlist);
</script>
<script type=”text/javascript”>
// utility functions for localstorage
function setObject(key, value) {
window.localStorage.setItem(key,
JSON.stringify(value));
};
function getObject(key) {
var storage = window.localStorage;
var value = storage.getItem(key);
return value && JSON.parse(value);
};
function clearStorage() {
// removes everything placed in localstorage
window.localStorage.clear();
};
</script>
<script>
var cmtlist = $('#cmtlist').html();
cmtlist = ‘<p><span class=”cmtname”’+cname+
‘</span >’+ctext+’</p>’+cmtlist;
setObject('cmtlist', cmtlist);
var cmtlist = getObject('cmtlist');
if (getObject('cmtlist') === null){
var cmtlist = '';
} else {
var cmtlist = getObject('cmtlist');
};
if ($('#txt1').val() === 'CLEAR ALL STORAGE NOW!'){
clearStorage();
};
</script>
</head>
<body>
<header id="banner">
<dl>
<dt>Matthew Wilson</dt><dd>
<imgsrc="http://www.uea.ac.uk/documents/2397319/2396777/UEA+logo/bc91b5b5-ab8e-4673-b1e6-1a4a9fd918ab?t=1359129534719" alt="sloth" /></dd>
</dl>
</header>
<nav>
<button class="navbutton" onClick="clearComment()">Clear Comment</button>
<button class="navbutton" onClick="saveComment()">Save Comment </button>
</nav>
<div id="main">
<div id="dtext">
<h4>Your comment</h4>
<input id="namebox" type="text" maxlength="32" size="20"
value="Name" />
<br />
<textarea id="txt1" class="textbox" rows="6"></textarea>
</div>
<h4>Comments</h4>
<div id="cmtlist">
</div>
</div>
</body>
</html>
Try this:
html
<button class="navbutton" onClick="clearComment()">Clear Comment</button>
<button class="navbutton" onClick="saveComment()">Save Comment </button>
<div id="dtext">
<h4>Your comment</h4>
<input id="namebox" type="text" maxlength="32" size="20" placeholder="Name" />
<br />
<textarea id="txt1" class="textbox" rows="6" placeholder="Your comment"></textarea>
</div>
<h4>Comments</h4>
<div id="cmtlist"></div>
javascript
// utility functions for localstorage
function setObject(key, value) {
window.localStorage.setItem(key, JSON.stringify(value));
}
function getObject(key) {
var storage = window.localStorage,
value = storage.getItem(key);
return value && JSON.parse(value);
}
function clearStorage() {
window.localStorage.clear();
}
// Clear inputfields and localstorage
function clearComment(){
$('#txt1').val('');
$('#namebox').val('');
clearStorage();
}
function saveComment(){
var cText = $('#txt1').val(),
cName = $('#namebox').val(),
cmtList = getObject('cmtlist');
if (cmtList){
cmtList.push({name: cName, text: cText});
setObject('cmtlist', cmtList);
}else{ //Add a comment
setObject('cmtlist', [{name: cName, text: cText}]);
}
bindCmt();
}
function bindCmt(){
var cmtListElement = $('#cmtlist'),
cmtList = getObject('cmtlist');
//Out with the old
cmtListElement.empty();
//And in with the new
$.each(cmtList, function(i, k){
cmtListElement.append( $('<p><span>'+ k.name +'</span>'+ k.text +'</p>') );
});
}
//Get the comments on page ready
$(function(){
bindCmt();
});
I don't know if I have understood the right context of 'storage', but according to some tutorials I used the following Javascript code, to enable a page to locally store (no session) submitted data, but when I close the page and reopen the page, the content do not appear.
script.js
function initiate()
{
var saveButton = document.getElementById('save');
var retrieveButton = document.getElementById('retrieve');
var deleteButton = document.getElementById('delete');
var reviewButton = document.getElementById('review');
saveButton.addEventListener('click', saveItem);
retrieveButton.addEventListener('click', retrieveItem);
deleteButton.addEventListener('click', deleteItem);
reviewButton.addEventListener('click', reviewAll);
}
function saveItem()
{
var key = document.getElementById('key').value;
var value = document.getElementById('value').value;
localStorage[key] = value;
}
function retrieveItem()
{
var data = document.getElementById('data');
var key = document.getElementById('key').value;
var value = localStorage[key];
data.innerHTML = '<div>' + key + ': ' + value + '</div>';
}
function deleteItem()
{
if (confirm('Delete?'))
{
var key = document.getElementById('key').value;
localStorage.removeItem(key);
data.innerHTML = '<div>Deleted.</div>';
}
}
function reviewAll()
{
for(var i = 0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
var value = localStorage[key];
data.innerHTML += '<div>' + key + ': ' + value + '<br></div>';
}
}
addEventListener("load", initiate);
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="mystyles.css" />
<script src="script.js"></script>
<title>Demo HTML5</title>
</head>
<body>
<section id="formSection">
<form name="dataForm">
<label for="key">Key: </label><br />
<input type="text" id="key" name="key" /> <br />
<label for="value">Value: </label><br />
<textarea name="value" id="value"></textarea><br />
<input type="button" id="save" value="Save" />
<input type="button" id="retrieve" value="Retrieve" />
<input type="button" id="delete" value="Delete" />
<input type="button" id="review" value="Review" />
</form>
</section>
<section id="data">
No data
</section>
</body>
</html>
If you are using the browser in privacy mode, it will clear all localStorage data when you close it.