I've created a list of some movie titles. If user has permission he can edit those names by pressing crtl + left click on title that he want to be changed.
P tag changes into input and on enter key ajax request is send with new name to the backend. That works fine. But I don't have any way to cancel name edit or block user from clicking on another title when one already is beeing edited
What I was trying to do is to check if user clicked something else that isn't an input and if so change back input to P tag but this isn't working.
jsFiddle.
$(document).ready(function() {
$('.nameChanger').on("mousedown", function(e) {
e.preventDefault();
if (e.ctrlKey) {
var $textElement = $(this);
var $input = $('<input class="inputElementNew" />').val($textElement.text());
var $textValue = $textElement.text()
$textElement.replaceWith($input);
if ($(e.target).closest('.inputElementNew').length === 0) {
//var $p = $('<p class="nameChanger" />').text($textElement.text());
console.log("back to oryginal")
//$input.replaceWith($p)
}
//used so you can click once on link element and new page won't open
$('.doubleLink').click(function() {
return false;
}).dblclick(function() {
window.location = this.href;
return false;
});
var send = function() {
var $p = $('<p class="nameChanger" />').text($input.val());
$input.replaceWith($p);
//ajax request is here
};
$input.keypress(function(e) {
if (e.keyCode == 13) {
console.log("changed")
$input.one('focusout', send)
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-1">Movie title 1</p>
</b></a>
</div>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-2">Movie title 2</p>
</b></a>
</div>
$(document).ready(function () {
function mouseDown() {
$('.nameChanger').on("mousedown", function (e) {
e.preventDefault();
if (e.ctrlKey) {
var $textElement = $(this);
var $input = $('<input class="inputElementNew" />').val($textElement.text());
var $textValue = $textElement.text()
$textElement.replaceWith($input);
$input.focus();
if ($(e.target).closest('.inputElementNew').length === 0) {
//var $p = $('<p class="nameChanger" />').text($textElement.text());
console.log("back to oryginal")
//$input.replaceWith($p)
}
//used so you can click once on link element and new page won't open
$('.doubleLink').click(function () {
return false;
}).dblclick(function () {
window.location = this.href;
return false;
});
var send = function () {
var $p = $('<p class="nameChanger" />').text($input.val());
$input.replaceWith($p);
//ajax request is here
mouseDown();
};
$(".inputElementNew").on("focusout", function () {
send();
})
$input.keypress(function (e) {
if (e.keyCode == 13) {
send();
}
});
}
});
}
mouseDown();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-1">Movie title 1</p>
</b></a>
</div>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-2">Movie title 2</p>
</b></a>
</div>
Your p-elements elements only get the Event-bindung once on document.ready().
The new created objects don't have an event-listener.
Best Practice would be creating the inputs and the p-elements at the same time and use css to show either one or the other and update with jquery.
If you want to use your approach you have to add the eventListener ".on" again to the P elements.
Please find the updated jsfiddle, Hope this solution help.
$(document).ready(function() {
$(document).on("mousedown",".nameChanger", function(e) {
e.preventDefault();
if (e.ctrlKey) {
var data_title = $(this).attr("data-title");
var data_val = $(this).html();
$(".inputElementNew").each(function(i,e){
$(this).replaceWith('<p class="nameChanger" data-title="'+data_title+'">'+$(this).val()+'</p>');
})
var $textElement = $(this);
var $input = $('<input class="inputElementNew" data-title="'+data_title+'"/>').val($textElement.text());
var $textValue = $textElement.text()
$textElement.replaceWith($input);
if ($(e.target).closest('.inputElementNew').length === 0) {
//var $p = $('<p class="nameChanger" />').text($textElement.text());
console.log("back to oryginal")
//$input.replaceWith($p)
$input.focus();
}
//used so you can click once on link element and new page won't open
$('.doubleLink').click(function() {
return false;
}).dblclick(function() {
window.location = this.href;
return false;
});
var send = function() {
var $p = $('<p class="nameChanger" />').text($input.val());
$input.replaceWith($p);
//ajax request is here
};
$input.keypress(function(e) {
if (e.keyCode == 13) {
console.log("changed")
$input.one('focusout', send)
}
});
$(".inputElementNew").on("focusout",function(){
$(this).replaceWith('<p class="nameChanger" data-title="'+data_title+'">'+$(this).val()+'</p>');
})
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-1">Movie title 1</p>
</b></a>
</div>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-2">Movie title 2</p>
</b></a>
</div>
Related
I have jQuery code that executes an AJAX request every time the text input is focused out. The thing I don't understand is when I focus back in the AJAX request gets executed. There's no focusin function defined. Code snippet below:
$(function() {
// some other functions here but no focusin function defined.
$( "#additem" ).click(function(e) {
e.preventDefault();
var _id = "new_pn", _holder = "Enter part number here", btnId = "post", btnIcon = "fa fa-save", btnText = " Add Serial", formId = "new-sn";
openModal(_id, _holder, btnId, btnIcon, btnText, formId);
});
var openModal = function(a,b,c,d,e, f) {
var txtInput = $("#myModal form input")[1], btn = $("#myModal form button")[0], icon = $("#myModal form i")[0], form = $("#myModal form")[0];
txtInput.id = a;
txtInput.placeholder = b;
btn.id = c;
icon.className = d;
form.id = f;
$($("#myModal form span")[1]).text(e);
$("#myModal").attr('style', 'display:block');
};
//Check serial before saving when text field is focusout. 2nd argument, #new-sn is a dynamically created form id.
$('#myModal').on('focusout', $('#new-sn input')[0], function() {
var sn = $("#serial").val();
if (sn) {
Promise.resolve(GetDocumentItems(serialsDb, sn)).then(function() {
console.log(sn.toUpperCase() + " already exists in the database");
}).catch(function() {
console.log(sn.toUpperCase() + " is cleared to save in database.");
});
}
});
});
What am I doing wrong here? Cheers
Added HTML code below:
<div id="myModal" class="modal">
<div class="modal-content">
<!--variable form id (depends on the caller)-->
<form>
<div class="container">
<span class="close">×</span>
<input id="serial" type="text" placeholder="Enter serial number here">
<!--2nd text box, variable id and placeholder (depends on the caller)-->
<input type="text">
<!--button variable id and i variable class (invoker dependent).-->
<button class="green"><i></i> <span></span></button>
</div>
</form>
</div>
</div>
html:
<header>
<h1>ENTER A TASK BELOW</h1>
<input type="text" id="task"><img id="add" src="add.png">
</header>
<div id="incomplete-tasks">
<h4>TO-DO LIST</h4>
<ul id="task-to-do">
</ul>
</div>
javascript / jquery:
$(document).ready(function() {
document.getElementById("add").addEventListener("click", function() {
var taskinput = document.getElementById("task").value;
if (taskinput) {
var tasktext = document.createTextNode(taskinput);
var list = document.createElement("li");
list.appendChild(tasktext);
var button = document.createElement("button");
button.setAttribute("class", "completed");
button.innerHTML = "X";
list.appendChild(button);
var toDoList = document.getElementById("task-to-do");
toDoList.insertBefore(list, toDoList.childNodes[0]);
document.getElementById("task").value = " ";
} else {
alert("Please enter a task");
}
});
$(document).on('click', "button.completed", function() {
$(this).closest("li").remove();
});
});
This is a simple to-do list I am working on. One of the things I have put in place is for an alert box to pop up if the user hits the "add" image/button without inputting anything into the field below "Enter a task".
However, something is wrong and it is allowing the user to add empty input values. I can not see what I am doing wrong here. Please can someone assit? Many thanks!
I made a small correction in your javascript/jquery code.In the if condition I added the trim() method to check if there is an empty characters string.
$(document).ready(function() {
document.getElementById("add").addEventListener("click", function() {
var taskinput = document.getElementById("task").value;
if ($.trim(taskinput)!== '') {
var tasktext = document.createTextNode(taskinput);
var list = document.createElement("li");
list.appendChild(tasktext);
var button = document.createElement("button");
button.setAttribute("class", "completed");
button.innerHTML = "X";
list.appendChild(button);
var toDoList = document.getElementById("task-to-do");
toDoList.insertBefore(list, toDoList.childNodes[0]);
document.getElementById("task").value = " ";
} else {
alert("Please enter a task");
}
});
$(document).on('click', "button.completed", function() {
$(this).closest("li").remove();
});
});
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/
My task is i have added multiple browse file clicking on add more button at the same time i have to view the file also after browsing the file for this i have used below code and i have succeded to browse the file on one browse box but i was unable to view all the image simultaneously.I am not getting how to do this
my check.html file
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="custom.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="file_wrapper" id="file_wrapper">
<div>
<span class="btn btn-default btn-file"><i class="fa fa-upload"></i>
Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/>
</span>
<span class="btn btn-success">
<a href="javascript:void(0);" class="add_image" title="Add field">
<span class="glyphicon glyphicon-plus" >Add more</span>
</a>
</span>
</div>
</div>
<hr />
<b>Live Preview</b>
<br />
<br />
<div id="dvPreview">
</div>
my second custom.js file is
// Add More field script
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_image'); //Add button selector
var wrapper = $('.file_wrapper'); //Input field wrapper
var fieldHTML = '<div><span class="btn btn-default btn-file"><i class="fa fa-upload"></i>Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/></span> <span class="btn btn-success"><span class="glyphicon glyphicon-minus">Remove</span></span></div>';
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
$(function () {
// View Image on Browse Script
$(".fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:200px;width: 300px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
Please help me
Thanks in Advance
every time you choose new image you remove previous one so delete first dvPreview.html("");
// Add More field script
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_image'); //Add button selector
var wrapper = $('.file_wrapper'); //Input field wrapper
var fieldHTML = '<div><span class="btn btn-default btn-file"><i class="fa fa-upload"></i>Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/></span> <span class="btn btn-success"><span class="glyphicon glyphicon-minus">Remove</span></span></div>';
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
$(function () {
// View Image on Browse Script
$(".fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
//dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:200px;width: 300px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
//dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
Bonjour, I am working on a jQuery project with the following scenario:
1/ There are 3 forms on the landing page for user to enter 3 different names.
2/ When user enter a name (#term1/term2/term3) in any of the #form, an image associated will appear.
The order of entering the names should not be restricted.
Eg. If user enters "Karen" in one of the forms, the name "Karen" will be printed and an associated image will be printed. If user enter "Baby Kevin", the name "Baby Kevin" will be printed next to "Karen" (ideally with a comma separating the names) and an associated image will be added next to the previous image.
I have encountered a problem where:
When a name is being entered, it would print the whole string of all the formsrather than appending it.
Eg. If I have entered "Wallace" previously, and when I enter "Karen" in another #form after, it would print "WallaceWallaceKaren".
If I submit the #form with the #button, the associated image would not show.
$(document).ready(function () {
$("#info").hide();
var displayContent = function () {
$("#info").show();
var content1 = $('#term1').val();
content1 = content1.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var content2 = $('#term2').val();
content2 = content2.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var content3 = $('#term3').val();
content3 = content3.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
var name1 = content1;
var $nameText1 = $("#name"),
str = name1;
html = $.parseHTML(str),
nodeNames = [];
$nameText1.append(html);
var name2 = content2;
var $nameText2 = $("#name"),
str = name2;
html = $.parseHTML(str),
nodeNames = [];
$nameText2.append(html);
var name3 = content3;
var $nameText3 = $("#name"),
str = name3;
html = $.parseHTML(str),
nodeNames = [];
$nameText3.append(html);
}
$('#search').click(displayContent);
$('#term1').keypress(function (event) {
if (event.which == 13) {
displayContent();
$('#figure').prepend('<img src = "http://placebear.com/100/100" />');
}
});
$('#term2').keypress(function (event) {
if (event.which == 13) {
$('#figure').prepend('<img src = "http://placebear.com/80/80" />');
displayContent();
}
});
$('#term3').keypress(function (event) {
if (event.which == 13) {
$('#figure').prepend('<img src = "http://placebear.com/50/50" />');
displayContent();
}
});
});
#content {
width: 400px;
height: 100px;
}
#figure {
position: fixed;
margin-left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="form">
<section id="fetch">
<input type="text" placeholder="Please enter your name here" id="term1" />
<button type="button" id="search">OK</button>
<input type="text" placeholder="Please enter your name here" id="term2" />
<button type="button" id="search">OK</button>
<input type="text" placeholder="Please enter your name here" id="term3" />
<button type="button" id="search">OK</button>
</section>
<section id="info">
<h4>Take a look inside with:</h4>
<section id="content">
<h5 id="name"></div>
<div id="figure"></div>
</section>
</section>
</section>
fiddle
I cleared out your code and its working now. You can give it a try.
$(document).ready(function(){
$("#info").hide();
var displayContent = function(){
$("#info").show();
var str = [],
imgs = ["http://placebear.com/100/100","http://placebear.com/101/101","http://placebear.com/102/102"];
$("#fetch input[type=text]").each(function(i){
var v = $(this).val();
if(v != ""){
str.push(v.toUpperCase());
if($("#figure").find("#image_"+i).length == 0){
$('#figure').prepend('<img src="' + imgs[i] + '" id="image_'+i+'" />');
}
}else{
$("#figure").find("#image_"+i).remove();
}
})
$("#name").html(str.join(", "));
}
$('#search').click(displayContent);
$("#fetch input[type=text]").keypress(function(event){
if(event.which == 13){
displayContent();
}
});
});
Plus your html has some problem <h5 id="name"></div> should be <h5 id="name"></h5>
Here is the fiddle https://jsfiddle.net/f9m65to6/1/
Instead of append use $("#term2").val($("#term2").val()+"newValue")