I'm display a text on screen and when I click it,I can edit the text using jquery. But I dunno how to reset the text that I edited to default and submit the text to database. If anyone know it please help me,thank in advance.
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
$(document).on('click', '.cmtedit', function (e) {
console.log(this);
TBox(this);
});
$("input").live('blur', function (e) {
RBox(this);
});
function TBox(obj) {
var id = $(obj).attr("id");
var tid = id.replace("cmt_edit_", "cmt_tedit_");
var input = $('<input />', { 'type': 'text', 'name': 'n' + tid, 'id': tid, 'class': 'text_box', 'value': $(obj).html() });
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var tid = id.replace("cmt_tedit_", "cmt_edit_");
var input = $('<p />', { 'id': tid, 'class': 'cmtedit', 'html': $(obj).val() });
$(obj).parent().append(input);
$(obj).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="sample">
<p id="cmt_edit_323" class="cmtedit">Sample Text</p>
</div>
<div>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-success" name="subtn">Submit</button>
</div>
</form>
Try this store the previous value with some variable .Then reset click add that previous value to function
var before;
jQuery.fn.extend({
live: function(event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
$(document).on('click', '.cmtedit', function(e) {
TBox(this);
});
$("input").live('blur', function(e) {
RBox(this);
});
$('.btn-primary').click(function() {
$("input").trigger('blur')
console.log(before)
$('.cmtedit').text(before)
})
function TBox(obj) {
before = $(obj).text()
console.log(before)
var id = $(obj).attr("id");
var tid = id.replace("cmt_edit_", "cmt_tedit_");
var input = $('<input />', {
'type': 'text',
'name': 'n' + tid,
'id': tid,
'class': 'text_box',
'value': $(obj).html()
});
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var tid = id.replace("cmt_tedit_", "cmt_edit_");
var input = $('<p />', {
'id': tid,
'class': 'cmtedit',
'html': $(obj).val()
});
$(obj).parent().append(input);
$(obj).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="sample">
<p id="cmt_edit_323" class="cmtedit">Sample Text</p>
</div>
<div>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="submit" class="btn btn-success" name="subtn">Submit</button>
</div>
</form>
Related
I am not understanding why the function goToProfile(otherUserId) is 'not defined' only some of the times.
For example, on the page, I have a link to a user that works fine by using the '.userProfileLink' click event.
<%= link_to image_tag(user.avatar.url(:medium)), "/profile/#{user.id}/view", class: "userProfileLink", :"value" => user.id, remote: true %>
Then I click #requestMeeting which renders this handlebars template:
<script id="request-meeting-form" type="text/x-handlebars-template">
<form id="requestMeetingForm">
<div class="form_section">
<h4 style="text-align:center;">Request 1 Hour Meeting</h4>
<br>
<div class="wrapper_input col_8_of_16">
<h4 class="label_standard">Date</h4>
<input type="text" id="meeting_date" class="input_standard datePicker" onfocus="this.blur()"></input>
<input type="hidden" id="alt_meeting_date" class="input_standard datePicker"></input>
</div>
<div class="wrapper_input col_4_of_16">
<h4 class="label_standard">Start Time</h4>
<input type="text" id="meeting_time" class="input_standard time_picker" onfocus="this.blur()"></input>
</div>
</div>
<div class="form_section">
<div class="wrapper_input">
<use xlink:href="#map"/></use></svg>
</div>
<br>
<div class="wrapper_input col_8_of_16">
<input type="text" name="location" id="locationField" placeholder="Location Name" class="input_standard" ></input>
</div>{{!--
--}}<div class="wrapper_input col_8_of_16">
<input type="text" name="location_address" id="addressField" placeholder="Location Address" class="input_standard"></input>
</div>
<input type="hidden" id="currentUser"></input>
</div>
<div id="mapLocation">
</div>
**************** IMPORTANT PART *********************
<div class="form_section submit_cancel">
<div class="wrapper_input cancel" >
<use xlink:href="#circleClose"/></svg>
</div>
********************************************
<div class="wrapper_input submit">
<div class="actions">
<button type="submit" class="btn_primary" id="requestMeetingButton" >Request Meeting <svg class="" ><use xlink:href="#sendPlane"/></svg></button>
</div>
</div>
</div>
</form>
</script>
When I try to call goToProfile again in the template above, I get an error that goToProfile is not defined.
application.js:
$(document).on('click', '#goToProfile', function(e) {
e.preventDefault();
var value = $(this).attr('value')
var otherUserId = parseInt(value);
$('#profileSection').empty();
goToProfile(otherUserId);
});
var ready;
ready = function(){
var currentUserId;
getCurrentUser().done(function() {
var currentUserId = currentUserId
});
$('.userProfileLink').click(function(e) {
var value = $(this).attr('value')
otherUserId = value;
goToProfile(otherUserId);
});
var profileSource = $("#user-profile").html();
var compiledProfile = Handlebars.compile(profileSource);
var languageSource = $("#languages").html();
var compiledLanguage = Handlebars.compile(languageSource);
var language = ""
var currentUserId;
var goToProfile = function(otherUserId) {
$.ajax({
url: '/get_user',
type: 'GET',
data: {otherUserId: otherUserId},
success: function(user) {
var profileInfo;
getUserImage(otherUserId).done(function() {
var profileInfo = {
first_name: user.first_name,
location: user.location,
bio: user.bio,
nationality: user.nationality,
userId: user.id,
userImage: userImage,
};
var profileTemplate = compiledProfile(profileInfo);
$('.yieldedInfo').empty();
$('.yieldedInfo').append('<div class="profileContainer">' + profileTemplate + '</div>');
});
getLanguagesUsers(user.id);
$('#requestMeeting').click(function(e) {
e.preventDefault();
requestMeetingForm(this.value);
});
},
error: function(err) {
console.log(err);
}
});
};
var getLanguagesUsers = function(userId) {
$.ajax({
url: '/user_languages',
type: 'GET',
data: {userId: userId},
success: function(languages) {
for(var i=0; i<languages.length; i++) {
if(languages[i].level != 5) {
var id = languages[i].language_id
var langUrl = '/languages/'+id;
$.getJSON(langUrl, function(lang) {
var language = lang.language
var languageInfo = {
language: language
};
var languageTemplate = compiledLanguage(languageInfo);
$('#learningLanguages').append(languageTemplate);
});
} else {
var id = languages[i].language_id;
var langUrl = '/languages/'+id;
$.getJSON(langUrl, function(lang) {
var language = lang.language
var languageInfo = {
language: language
};
var languageTemplate = compiledLanguage(languageInfo);
$('#fluentLanguages').append(languageTemplate);
});
};
};
},
error: function(err) {
console.log(err);
}
});
};
};
$(document).ready(ready);
$(document).on('page:load', ready);
How can I make goToProfile() available to be called all the time?
Thanks!
You can do what you need by binding the click event handler at the same scope level as the function it needs to call...
var ready = function(){
$(document).on('click', '#goToProfile', function(e) {
e.preventDefault();
var value = $(this).attr('value')
var otherUserId = parseInt(value);
$('#profileSection').empty();
goToProfile(otherUserId);
});
// the rest of your ready function goes here
};
If you do it that way then the event handler has access to the goToProfile function as they're both within the ready function. Nothing outside that function can access the private methods inside it.
I have the following markup
<div class="col-md-4">
<div class="row">
<img name="previewImage" alt="" src="" style="max-height:300px;max-width :350px;">
</div>
<div class="row">
<button name="btnPushPhoto" type="button" class="btn btn-default" tabindex="-1">Push</button>
<button name="btnRemovePhoto" type="button" class="btn btn-default" tabindex="-1">Remove</button>
</div>
</div>
When I click on the remove photo button, I'm able to set my image to null (in the server side), however at the client side, I'm having some difficulties locating the image tag, and refresh it.
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
var img = $(this).parent().parent().find('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
Nothing seems to happen here. No error in the browser's console.
This is the output of console.log(img);
[prevObject: x.fn.x.init[0], context: undefined, selector: "[name=previewImage]"]
You should store the $(this) in some variable before post request since inside the callback, this refers to the jqXHR object of the Ajax call, not the element the event handler was bound to :
_this = $(this);
Then you could use parents() instead :
var img = _this.parents('.col-md-4').find('[name="previewImage"]');
Hope this helps.
Try this:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
var $this = $(this); //Insert this line
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = $this.closest("div.col-md-4").find("img"); //USE $this
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
You should move img definition before the $.post function:
$(document).on("click", "[name=btnRemovePhoto]", function () {
var img = $(this).parent().parent().find('[name=previewImage]');
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
//var img = $(this).closest('[name=previewImage]');
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
I think the way you are searching/looking at the relationship needs to be edited slightly. There are a few jquery methods that may help but I usually like to map out the relationships in my head like below:
<div name="PARENT_of_PARENT_of_X">
<div name="Sibling_of_PARENT_of_X OR child_of_PARENT_of_PARENT_of_X>
<img name="Child_of_SIBLING_of_PARENT_of_X OR CHILD_of_PARENT_of_PARENT_of_X" />
</div>
<div name="PARENT_of_X">
<button ></button>
<button name="SOURCE X" >Remove</button>
</div>
</div>
You could use jQuery selector "closest"
https://api.jquery.com/closest/
$(document).on("click", "[name=btnRemovePhoto]", function () {
var clickedButton = $(this);
var r = confirm("Are you sure you want to remove the photo?");
if (r == true) {
var uniqueId = $(this).data('uniqueId');
$.post($("#remove-photo-url").val(), { uniqueId: uniqueId })
.done(function () {
var img = clickedButton .closest("div.col-md-4").find("img");
console.log(img);
img.attr('src', '');
img.attr('src', img.attr('src') + '?' + Math.random());
});
}
});
I have the script bellow and i want to get the id of the child removed
<div class="right respleft">
<div class="section-title" id="divin">Ajout d'un champ</div>
<form class="tiny_form" id="form-step2">
<input type="text" id="fiel" placeholder="Nom du champ" /><br/>
<select class="form-control" id="champs">
</select>
<i class="fa fa-plus"></i><br/>
<div id="extender"></div>
</form>
</div>
<div class="sep seppage"></div>
<div class="clear"></div>
<div id="bottom-submit" class="inner clear">
<input type="submit" class="page-next center btn btn-lg btn-default" value="Créer" />
</div>
{% endblock %}
{% block javascripts %}
<script>
//add input
$('a#add_btn').click(function () {
var x = document.getElementById("fiel");
var selected= x.value;
var c = document.getElementById("champs");
// var option = document.createElement("option");
var strUser = document.getElementById("champs").value;
var valChamps=document.getElementById("fiel").value;
$('<p><input type="text" class="highlight_orange" name="items[]" id="' + strUser+ '" value="' + valChamps+ '" />' +
'<a class="delete" href="#step2" id="' + strUser + '"><i class="fa fa-trash-o"></i></a></p>').fadeIn("slow").appendTo('#extender');
c.remove(c.selectedIndex);
i++;
return false;
});
//fadeout selected item and remove
$("#form-step2").on('click', '.delete', function () {
var item = $(this).closest('input');
var id = item.attr('id');
$(this).parent().fadeOut(300, function () {
$(this).empty();
return false;
});
});
function addList(){
var select = document.getElementById("champs");
for(var i = 100; i > 0; --i) {
var option = document.createElement('option');
option.text = 'champ libre '+i;
option.value =i;
select.add(option, 0);
}
}
addList();
</script>
my problems is how to get the id of the removed input text after clicking on remove button.
this is picture of the output
output
Thanks for your helps
You can use siblings method to get the id of input element
//fadeout selected item and remove
$("#form-step2").on('click', '.dynamic-link', function () {
var myId = $(this).siblings('input[type=text]').attr('id');
alert(myId)
$(this).parent().fadeOut(300, function () {
$(this).empty();
return false;
});
});
You can use getAttribute() function:
// your stuff
var myId = c.getAttribute("id");
c.remove(c.selectedIndex);
// more stuff
EDIT
Maybe you need it here:
//fadeout selected item and remove
$("#form-step2").on('click', '.delete', function () {
$(this).parent().fadeOut(300, function () {
var myId = $(this).attr('id');
$(this).empty();
return false;
});
});
Be more specific please
EDIT2
That's the solution:
//fadeout selected item and remove
$("#form-step2").on('click', '.delete', function () {
$(this).parent().fadeOut(300, function () {
var myId = $(this).find('input[type=text]').attr('id');
$(this).empty();
return false;
});
});
See it working: http://jsfiddle.net/vWPJf/57/
Hi I'm trying to add "children" list items to "family" lists. I have a first form to create the families and a second form which is a select box to create the children and add them to a selected family from the select box. The Ol's ids are dynamically created and the drop down's options dynamically created.
When an option is created, the values are incremented every time a family and option is made.
My plan is to reference the OL families by using the options, basically corresponding to the family by the time it is created.
For example when I make a family1, there will be an option created with that family1 with a value 1, and when family2 is created, an option 2 is created with a value of 2.
I'm trying to append children to the family but I have no idea how to reference the OL's ids
this is what I have so far
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
var i = 1;
$(document).on('click', "#submit", function () {
var str = ' '
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each(function () {
str = str + $(this).val() + ' ';
$(this).val('');
});
$("<ol>", {
text: str,
id: "family+" + i
}).appendTo("#container").append($('<button />', {
'class': 'btn2',
text: 'Remove'
}));
$('#select').append($('<option />', {
text: family,
value: i
}));
i++;
});
// Append items functions
$(document).on('click', "#submit2", function () {
var child = prompt("Please enter the child you want to add");
var e = document.getElementById("select");
var str = e.options[e.selectedIndex].value;
$('<li>', {
text: child
}).appendTo( ? ? ? ).append($('<button />', {
'class': 'btn',
text: 'Remove'
}))
});
//delete items functions
$(document).on('click', '.btn', function () {
$(this).closest('li').remove();
});
// delete the list
$(document).on('click', '.btn2', function () {
$(this).parent().next().remove();
$(this).closest('ol').remove();
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id = "child">
<select id ="select">
</select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id = "container">
</div>
</body>
</html>
Tip and help are appreciated
http://jsfiddle.net/Jnewguy/4LVTz/
Try
$(document).ready(function () {
var i = 1;
var $famname = $('#famname');
var $finputs = $('#family input[type = text]').not('#famname');
$(document).on('click', "#submit", function () {
var family = $famname.val();
var $ol = $("<ol>", {
id: "family-" + i
}).appendTo("#container");
$('<li />', {
text: family
}).append($('<button />', {
'class': 'btn2',
text: 'Remove'
})).appendTo($ol);
$finputs.each(function () {
$('<li />', {
text: this.value
}).appendTo($ol);
$(this).val('');
});
$('#select').append($('<option />', {
text: family,
value: i
}));
i++;
});
// Append items functions
var $select = $('#select')
$(document).on('click', "#submit2", function () {
var child = prompt("Please enter the child you want to add");
$('<li>', {
text: child
}).appendTo('#family-' + $select.val()).append($('<button />', {
'class': 'btn',
text: 'Remove'
}))
});
//delete items functions
$(document).on('click', '.btn', function () {
$(this).closest('li').remove();
});
// delete the list
$(document).on('click', '.btn2', function () {
$(this).parent().next().remove();
$(this).closest('ol').remove();
});
});
Demo: Fiddle
I'm trying to write a jQuery code that works in this way:
When the page is loaded, it is presents only one field.
Selecting an option from that field, a new field is opened and the option have to be all the option of the first , except the option selected. And so on, also for the other created.
The jsfiddle is shown here
var globalObj = {};
var selectedObj = {};
var unselectedObj = {};
var currentSelection = "";
function deleteByVal(obj,val) {
for (var key in obj) {
if (obj[key] == val) delete obj[key];
}
}
$(document).ready(function () {
$(document).on('click', 'target', function(){
var curSelected = $(this).find(":selected").text();
});
$("#select1").one('click',function(){
$(this).children().each(function () {
globalObj[this.value] = this.innerHTML;
});
unselectedObj = globalObj;
});
$(document).on('change', '.prova > .target', function () {
$('div').removeClass('prova');
var $mySelect = $('<select>', {
class: 'target'
});
var selectedValue = $(this).find(":selected").text();
var found = 0;
$.each(selectedObj, function (val, text) {
if (val === selectedValue) {
found++;
}
});
if (found===0) {
selectedObj[this.value] = selectedValue;
deleteByVal(unselectedObj,selectedValue);
}
console.log(selectedValue);
console.log(selectedObj);
console.log(unselectedObj);
var obj = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML!=selectedValue) {
//code
obj[this.value] = this.innerHTML;
}
});
console.log("Questo rappresenta obj:");
console.log(obj);
console.log("stampa obj conclusa");
$( "select" ).not(this).each(function( index ) {
var temp = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
$this = $(this);
console.log("stampa temp");
console.log(temp);
console.log("fine stampa temp");
});
$.each(unselectedObj, function (val, text) {
$mySelect.append($('<option />', {
value: val,
text: text
}));
});
var $input = $('<input>', {
type: 'number',
style: 'width: 35px',
min: '1',
max: '99',
value: '1'
});
var $button = $('<button>', {
type: 'button',
class: 'remove_item',
text: 'delete'
});
$(this).parent().after($('<br>', {
class: 'acapo'
}), $('<div>', {
class: 'prova'
}).append($mySelect, $input, $button));
$(this).unbind('change');
$(this).unbind('click');
$(this).on('click', function(){
currentSelection = $(this).find(":selected").text();
});
$(this).on('change',function(){
console.log("nuovo bind");
var selectedValue = $(this).find(":selected").text();
if (currentSelection !== selectedValue) {
console.log(currentSelection + " to "+ selectedValue);
$( "select" ).not(this).each(function( index ) {
$(this).append($('<option />', {
value: currentSelection,
text: currentSelection
}));
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
});
}
});
});
});
The code has some problems and I was thinking to use an existing plugin instead of that code. Is there anyone that knows a plug-in which makes that work?
Here's an option using javascript templating. I'm declaring my available options at the top in an array, thus separating my data model from the UI. I'm using the handlebars library to then compile a template and append it into the DOM. Fiddle: http://jsfiddle.net/LNP8d/1/
HTML/Handlebars
<script id="select-template" type="text/x-handlebars-template">
<div>
<select class="target" id ="select-{{id}}">
<option value="">Select an option…</option>
{{#each options}}
{{#unless selected}}
<option data-option-key="{{#key}}" value="{{value}}">{{label}}</option>
{{/unless}}
{{/each}}
</select>
<input type="number" style="width: 35px" min="1" max="99" value="1">
</div>
</script>
<div id="container">
</div>
Javascript
//Declare the available options
var options = {
option1: {
value: 1,
label: "Option 1"
},
option2: {
value: 2,
label: "Option 2"
},
option3: {
value: 3,
label: "Option 3"
},
option4: {
value: 4,
label: "Option 4"
},
}
source = $("#select-template").html(),
template = Handlebars.compile(source),
onScreen = 0;
//Adds another select menu
var showSelect = function(){
onScreen++;
$("#container").append(template({id:onScreen, options:options}))
};
//Listens to change events
$("body").on("change", ".target", function(){
options[$(this).find(":selected").data("option-key")].selected = true;
showSelect();
});
//Initialises the UI
showSelect();
Please note: this is not a complete example. If you decide to use this method, you'll need to add some checks for what happens when the options run out and if someone changes an option. I hope it's successful in showing you an alternative a potentially more flexible method though.
I think you are looking for something like this:
http://codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/