I know this question has been asked a million times, but I can't seem to get anything to work. I am trying to have the value of the input change when I click one of the links which is working fine, but I'd also like to submit the form automatically as well, without a submit button as soon as a link is clicked. At the moment it doesn't work unless I click the input field. Also I can't add id's to the links. This is what I have so far.
var $Form = $('form'), $Container = $('#container');
$Container.hide();
$Form.on('click', function(p_oEvent){
var sUrl, sMovie, oData;
p_oEvent.preventDefault();
sMovie = $Form.find('input').val();
sUrl = 'https://www.omdbapi.com/?t=' + sMovie + ''
$.ajax(sUrl, {
complete: function(p_oXHR, p_sStatus){
oData = $.parseJSON(p_oXHR.responseText);
console.log(oData);
$Container.find('.title').text(oData.Title);
$Container.find('.plot').text(oData.Plot);
$Container.find('.poster').html('<img src="' + oData.Poster +
'"/>');
$Container.find('.year').text(oData.Year);
$Container.show();
}
});
});
$(function () {
$('a').on('click', function () {
var text = $('#text');
text.val($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
rocky<br>
Back To The Future<br>
Spaceballs<br>
<form id="omdbform">
<input type="text" name="movie" placeholder="movie title" id="text" onchange="this.form.submit();">
</form>
<div id="container">
<h3 class="title">Title</h3>
<span class="year">Year</span>
<span class="poster">Poster</span>
<p class="plot">Plot</p>
</div>
Any help would be greatly appreciated.
Added link examples
filename1.jpg
filename2.jpeg
Change your link function to below :
$(function () {
$('a').on('click', function () {
var text = $('#text');
var fileName =$(this).text();
fileName = fileName.replace(/\.[^/.]+$/, "");
text.val(fileName);
$Form.click();
});
});
try the following code
var $Form = $('form')
$Container = $('#container');
$Container.hide();
$("body").on("submit", "form", function(p_oEvent){
var sUrl, sMovie, oData;
p_oEvent.preventDefault(); sMovie = $Form.find('input').val();
sUrl = 'https://www.omdbapi.com/?t=' + sMovie + ''
$.ajax(sUrl, {
complete: function(p_oXHR, p_sStatus){
oData = $.parseJSON(p_oXHR.responseText);
console.log(oData);
$Container.find('.title').text(oData.Title);
$Container.find('.plot').text(oData.Plot);
$Container.find('.poster').html('<img src="' + oData.Poster +
'"/>');
$Container.find('.year').text(oData.Year);
$Container.show();
}
}); });
$('a').on('click', function (e) {
e.preventDefault();
var text = $('#text');
text.val($(this).text());
$("form").submit();
});
Before using the "on" read http://api.jquery.com/on/
Related
I am trying to implement edit functionality for a HTML element.
Right now my html-pug code is as below
div
label(for="todo" id="todo" + index class="ind-todo-list") test1
button(type="submit" id="todo" + index class="btn" onclick="editTodo()" ) Edit
button(type="submit" id="todo" + index class="btn" onclick="deleteTodo()" ) Delete
Jquery is as below
$(document).ready(function() {
$(".ind-todo-list").on("click" , function(){
var todoid = $(this).attr("id");
var newInput = document.createElement("input");
newInput.type="text";
newInput.name="todo";
$("#" + todoid).html(newInput);
});
});
But everytime I am clicking at the test1 my page reloading again even after input field added.
What I am trying to achieve is
- when I click at test1, I will have input box opened, where I can edit the test1 and save changes. But I am stuck here.
Thank you.
Edit 1
I have added event.preventDefault() but still experiencing same same
$(document).ready(function() {
$(".ind-todo-list").on("click" , function(event){
event.preventDefault();
var todoid = $(this).attr("id");
console.log("Todoid " + todoid);
console.log($("#" + todoid).html());
var newInput = document.createElement("input");
newInput.type="text";
newInput.name="todo";
//newInput.id=todoid;
//$("#" + todoid).html("<input type='text' name='todo' id='"+todoid+"'>");
$("#" + todoid).html(newInput);
});
Edit 2 - ID fix
div
label(for="todo" id="todo" + index class="ind-todo-list") #{todo.todo}
button(type="submit" id="todoedit" + index class="btn" ) Edit
button(type="submit" id="tododeleteq" + index class="btn" ) Delete
$(".ind-todo-list").on("click" , function(e){
//add an event to prevent default action on the element
e.preventDefault();
});
});
I have markup like so:
$('label.duplicate').click(function(e) {
e.preventDefault();
var _for = $(this).attr('for');
$('input[name="' + _for + '"]').clone().insertBefore($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input_one[]">
<label class="duplicate" for="input_one[]">Add another car</label>
This doesn't duplicate, or provide an error so I don't know why this is not working?
It is working, but you need to wait for the dom-structur to load before you run you code. Put everything inside documet.ready like this:
$(document).ready(function() {
$('label.duplicate').click(function(e) {
e.preventDefault();
var _for = $(this).attr('for');
$('input[name="' + _for + '"]').clone().insertBefore($(this));
});
})
Or insert your code dead last on you page. Read more about this here: https://learn.jquery.com/using-jquery-core/document-ready/
<input type="text" name="input_one[]">
<label class="duplicate" for="input_one[]">Add another car</label>
just .duplicate is enough to duplicate:
$(function(){
$('.duplicate').click(function(e) {
e.preventDefault();
var _for = $(this).attr('for');
$('input[name="' + _for + '"]').clone().insertBefore($(this));
});
}
I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>
When I write some text in the input field. And want it displayed below the input field, when pressing the submit button it disappears. I don't know why.
Live Demo
HTML:
<textarea id ="comments" cols="30" rows="3"></textarea>
<input type="submit" value="Submit" id="submit"/>
<div id="divComments"></div>
Jquery:
function addComment(name1) {
var container = $('divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />');
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
You missed the # for id selector, change
var container = $('divComments');
to
var container = $('#divComments');
See the fixed demo.
The selector for the divComments div is missing the # for the id selector.
function addComment(name1) {
var container = $('#divComments');
var inputs = container.find('label');
var id = inputs.length + 1;
var div = $('<div />');
$('<label />', {
id: 'comment' + id,
text: name1
}).appendTo(div);
div.appendTo(container);
}
$('#submit').click(function () {
addComment($('#comments').val());
$('#comments').val("");
});
Working fiddle.
As well as fixing the following line to add a hash
var container = $('#divComments');
you will also want to change the submit function:
$('#submit').click(function (e) {
e.preventDefault();
addComment($('#comments').val());
$('#comments').val("");
});
This will stop the form actually been submitted (and reloading the page) - which is probably the reason for your text disappearing. If you don't have a form surrounding your inputs then you don't need to bother with the second part of this answer.
I'm trying to do something similar to this:
$('#dropdown1').change(function() {
window.location = $(this).val();
});
I need to build a page with 2 dropdown lists and a textbox, and I need the values for each one to be stored and then appended to the URL when the form is submitted.
The URL needs to look similar to this when all options have been selected:
http://www.domain.co.uk/search-results/?searchOptions=dropdown1=value1|dropdown2=value2|textarea1=value3
I've figured out how to store the values of the dropdowns but I can't seem to append it to the url.. Here's where I got to:
<script type="text/javascript">
function getValues() {
var priceTo = document.form.priceTo.value;
//alert (priceTo);
}
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo
return false;
});
});
</script>
<body>
<form id="form" name="form">
Price:
<select name="priceTo" id="priceTo" onchange="getValues()">
<option value="5000">Up to £5,000</option>
<option value="10000">Up to £10,000</option>
<option value="20000">Up to £20,000</option>
<option value="40000">Up to £40,000</option>
<option value="80000">Up to £80,000</option>
</select>
<input type="submit" id="submit" value="submit"/>
</form>
</body>
For some reason this goes to:
http://www.domain.co.uk/search-results/?searchOptions=priceto=[object%20HTMLSelectElement]
EDIT:
I finally got it working on most browsers, including IE8 with this code:
<script type="text/javascript">
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.selektvolvocars.co.uk/selekt-search-results/?searchOptions='
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value + model.options[model.selectedIndex].value + '%7Czipcode=' +document.getElementById('zip').value + '%7Cproximitydistance=50'
e.preventDefault();
});
});
</script>
For some reason though it doesn't work in IE9... makes no damn sense to me, it just spits out a completely jumbled up URL. Any ideas?
your priceTo is the select list. Use the following to get the selected value:
$('#form').submit(function(e) {
window.location.href = initialURL + priceTo.options[priceTo.selectedIndex].value
e.preventDefault();
});
If I've understood correctly:
var initialURL = 'http://www.domain.co.uk/search-results/?searchOptions=priceto='
$('#form').submit(function(e) {
window.location = initialURL + $("#priceTo").val() + "|" + $("#anyOtherSelects").val();
e.preventDefault();
});
You can remove the rest of the Javascript.
You can use a little helper function which gets the id of a <select> or <input> element and returns it with its value. For example:
<script type="text/javascript">
//Helper function to return id and value. The id parameter shouldn't have the # sign at its beginning
function getIdVal( id ) {
return id + "=" + encodeURIComponent( $("#"+id).val() );
}
//run this when the document is loaded and ready
$(document).ready(function() {
//var zip = $('#zip').val();
var initialURL = 'http://www.domain.co.uk/search-results/?'
$('#form').submit(function(e) {
window.location.href = initialURL + getIdVal( "priceFrom" ) + "|" + getIdVal( "priceTo" );
return false;
});
});
</script>
Notes:
You get the value of the current <option> selected in a <select> element using $(...).val().
It is a good programming practice to use encodeURIComponent() for encoding the values just to make sure that no strange character is going to break your convention of using = and | as record and field separator in the search query URL.