convert text to editable text input and save into db - Laravel - javascript

I'm currently implementing a feature that somebody can add addresses on my page. He can do this via a simple form. What I have now (to print the addresses) is:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: {{$address->name}}<br/>
Straße: {{$address->street}}<br/>
PLZ: {{$address->plz}}<br/>
Ort: {{$address->city}}<br/>
<a type="button" class="btn btn-info" href="/editAddress/{{$address->id}}">Bearbeiten</a>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
The variable addresses is passed into the view from the controller.
What I'm trying to achieve now, is that the user can simply click on one of those address parts, like name, straße, plz and ort, and it's converted to an input field, so the value can be changed. Then, when leaving the focus (so clicking somewhere else (or maybe add a save button next to it)), the new data has to be sent to the controller by ajax (the request itself should be no problem then). But: How can I convert it to an input field and how can I then convert it back and react to it (to then send the ajax request)?
I searched in the internet, but didn't find something...
Edit: found a fiddle here (http://jsfiddle.net/yXcZG/3) that does nearly what I want, but I have the problem, that it doesn't seem to keep the format, 1. it has much more space between the lines and: when clicking on it to edit, the input field jumps to the bottom of the page and doesn't stay on the same position. Also I just want the variables to be editable, not the text before the :.
So this is what I tried: (of course the AJAX thing is still missing, but first the other thing has to work)
In JS:
$(document).on('click', '.editableText', function (e) {
console.log(this);
TBox(this);
});
$("input").live('blur', function (e) {
RBox(this);
});
function TBox(obj) {
var id = $(obj).attr("id");
var input = $('<input />', { 'type': 'text', 'id': id, 'class': 'editableText', 'value': $(obj).html() });
$(obj).parent().append(input);
$(obj).remove();
input.focus();
}
function RBox(obj) {
var id = $(obj).attr("id");
var input = $('<p />', { 'id': id, 'class': 'editableText', 'html': $(obj).val() });
$(obj).parent().append(input);
$(obj).remove();
}
HTML:
#foreach($addresses as $address)
#if($address->typeOfAddress==0)
Name: <span id="addressName{{$address->id}}" class="editableText">{{$address->name}}</span><br/>
Straße: <span id="addressStreet{{$address->id}}" class="editableText">{{$address->street}}</span><br/>
PLZ: <span id="addressPLZ{{$address->id}}" class="editableText">{{$address->plz}}</span><br/>
Ort: <span id="addressCity{{$address->id}}" class="editableText">{{$address->city}}</span><br/>
<a type="button" class="btn btn-danger deleteAddressButton" href="/deleteAddress/{{$address->id}}">Löschen</a>
<br/><br/>
#endif
#endforeach
Edit2: Found this answer on stackoverflow too (https://stackoverflow.com/a/6814092/3375021), so use contenteditable, but I have the problem, that I on blur neither know, which address should be changed in the database, nor which part of the address..

If you're looking for a jQuery working solution you can go with this
JsFiddle example
You have a listener for when you click an element that is editable, it'll take the value of it and put it inside an input.
After you blur you can take this value and do whatever you want with it..
Here is the javascript (jQuery) part.
$(function(){
$('body').on("click", ".changeable", function(e){
var text = $(this).text();
$(this).html("<input type='text' class='input-editable' value='" + text + "'>");
$(this).find('input').focus();
});
$('body').on("blur", ".input-editable", function(e){
var text = $(this).val();
$(this).parent().html(text);
console.log("Value changes to: " + text);
});
});

I think you should be using <?php echo $variable; ?> instead of blade {{$variabl}}
If you going to store a html tags or js into your database then you need to not use blade to echo it, you should use php simple echo function instead

Related

Selecting and Appending a <li> based on `data-id`

The application which I have build in Laravel could enable the user to edit certain models etc. On the create event, a jstree is generated to appoint specific data features to variables. Now, the jstree has to be adjusted but the variables which were already stored need to be visualized again! This way, the user would have to re-enter all the data.
On the selection of a jstree node, the following code is executed:
$(document).on('submit','form:not(.secret)',function(event){
event.preventDefault();
var id = $('.modal-body input[type=hidden]').val();
console.log(id);
var li = $('li[id='+id+']');
var field = li.data('id');
console.log(field);
var text = li.text();
console.log(text);
var value = $('.modal-body select').val();
console.log(value);
$("#html1").jstree('rename_node', '#'+id, text+' <span class="glyphicon glyphicon-arrow-right"></span> '+value);
$("#html1").jstree(true).set_icon('#'+id, "glyphicon glyphicon-check");
$('form.secret').append('<input type="hidden" name="'+field+'" value="'+value+'"/>');
});
Now, I need to pass an array of already selected variables. The JSON is formated like:
{"KnSubject":{"Element":{"Fields":{"StId":"{{Omschrijving}}","Da":"{{Omschrijving}}","SaId":"{{Omschrijving}}"}},"Objects":[]}}
So, the ID is not stored. But when looking through the console. The key value is partially called in the data-id attribute.
The code which I have now loops through these keys, but now I need to append the jstree node based on the partial key which is called. Could someone help me with this?
The which i have now:
#foreach ($text_data as $value)
$("#html1").jstree('rename_node', '#'+id, text+' <span class="glyphicon glyphicon-arrow-right"></span> '+value);
$("#html1").jstree(true).set_icon('#'+id, "glyphicon glyphicon-check");
$('form.secret').append('<input type="hidden" name="'+field+'" value="'+value+'"/>');
#endforeach

input cannot be reset to the default using angular.copy

I am displaying user first name in div and have an edit button. Once I click edit, a textbox appears so I can edit the name.
When I click on edit, the textbox takes the same text displayed on the div and if I cancel the edit, I want the changes back to the default value which is the div... Here is my code:
View:
<td>
<div ng-show="!nameElements" class="item_list">{{u.fName}}</div>
<div ng-show="nameElements">
<input type="text" id="ufn" ng-model="userfName">
<i class="fa fa-floppy-o fa-lg" aria-hidden="true"></i>
</div>
Angular Controller:
$scope.defaultfName = angular.copy(response.data[0].fName);
.
.
.
$scope.toggle = function (elem) {
$scope.userfName = $scope.defaultfName;//reset input
$scope.nameElements = !$scope.nameElements;//for the ng-view
};
My problem is, when I change the text and click on cancel to hide the input as well as reset the text, the text doesn't reset! Which means the same changes remains when I click on edit again.
Please help
Angular.copy works fine but for $scope.defaultfName.
remove Angular.copy from that line and put it for $scope.userfName.
$scope.defaultfName = angular.copy(response.data[0].fName); //Copy is optional
.
.
.
$scope.toggle = function (elem) {
$scope.userfName = angular.copy($scope.defaultfName); //no more reference passing!
$scope.nameElements = !$scope.nameElements;
};
And for preventing extra problems from multiple hitting or ... i suggest you to put the code in $scope.applyAsync, like this:
$scope.toggle = function (elem) {
$scope.$applyAsync(function() {
//rest of codes ...
});
};

How to set text box to appear blank after .click function

So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>

Javascript fill inputs on button click with AJAX

Everything almost works! i just need to find out why the code below won't give me more than the first buttons values.
public static function getProjectOnSearch($inp){
return DB::table('projecten')
->select(DB::raw('titel,status,prioriteit,soort,projectnaam,projecturl
,gebruikersnaam,wachtwoord
,gebruiker_id,omschrijvingproject'))
->where('projectnaam', 'LIKE', '%'.$inp.'%')
->get();
}
I want to fill in some input fields with values from my database upon clicking an button. I have the code working to fill in an name and click on the search button to fill the inputs. That works great. When I use that code with the other button it won't work. see my code below.
Javascript code :
<script type="text/javascript">
$("#wijzigKnop2").on("click",function(){
var email2 = $('#zoeknaam2').val('');
$('#titel2').val('');
$('#status2').val('');
$('#prioriteit2').val('');
$('#type2').val('');
$('#projectnaam2').val('');
$('#projecturl2').val('');
$('#gebruikersnaam2').val('');
$('#wachtwoord2').val('');
$('#omschrijving2').val('');
$.ajax({
method: "POST",
url: "/updateProjectData",
data: { input: email2 ,
_token: "{{ csrf_token() }}"
}
})
.done(function( msg ) {
$('#titel2').val(msg[0].titel);
$('#status2').val(msg[0].status);
$('#prioriteit2').val(msg[0].prioriteit);
$('#soort2').val(msg[0].soort);
$('#projectnaam2').val(msg[0].projectnaam);
$('#projecturl2').val(msg[0].projecturl);
$('#gebruikersnaam2').val(msg[0].gebruikersnaam);
$('#wachtwoord2').val(msg[0].wachtwoord);
$('#omschrijving2').val(msg[0].omschrijvingproject);
});
});
</script>
HTML Button with hidden input for value (normally the value would be typed in but this button will get the value from an HTML table which generates a row throught a foreach)
<input type="hidden" value="{{$project->projectnaam}}"
id="zoeknaam2" name="zoeknaam2" class="form-control" placeholder="Projectnaam">
<button class="btn btn-success btn-xs" id="wijzigKnop2" name="zoekProject" type="button">
<i class="glyphicon glyphicon-pencil"></i>
</button>
Any answers or ideas are very welcome thanks in advance for posting!
Please check
var email2 = $('#zoeknaam2').val('');
this should be not blank
var email2 = $('#zoeknaam2').val();
If you get proper value in at server side then problem at server side code.
To check on response,do
console.log(JSON.stringify(msg));
As per questioner server side solving
public static function getProjectOnSearch($inp){
return DB::table('projecten') ->select(DB::raw('titel,status,prioriteit,soort,projectnaam,projecturl ,gebruikersnaam,wachtwoord ,gebruiker_id,omschrijvingproject')) ->where('projectnaam', 'LIKE', '%'.$inp.'%') ->get();
}
fixes all things.
Get the value of the element then clear it.
var email2 = $('#zoeknaam2').val();
$('#zoeknaam2').val('');

JQuery, Javascript button

Sorry for the vague title, couldn't think of how to title my question. So I've made a html/css table wherein I placed an edit button for each row. Pressing the button would transform a certain text field into a text-input field there by allowing the user to edit the data inside; at the same time the edit button then transforms to save button. After editing , the user then would press the save button and the text-input field would then revert back into a text field and the save button back to an edit button. But it's not entirely working
This is my problem, after editing the data inside, upon pressing the save button, the data inside is deleted and replaced with: <input type= and outside the text-input field is: " />
and the save button remains as is, a "SAVE" button and not back to an "EDIT" button
here's the script:
$(document).ready(function () {
// listen for email edit button click
$("button#edit").on('click', function () {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
alert(email);
// change button from edit to save
$(this).attr('id', 'save-email').html('SAVE');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="' + email + '" />');
});
// listen for email save button click
$("button#save-email").on('click', function () {
// get new email inline to this save button
var newEmail = $(this).parents('tr').find($('input#user-email')).val();
alert(newEmail);
// change input field back to display
$(this).parent().siblings('td.email').html(email);
// change button from save to edit
$(this).attr('id', 'edit').html('EDIT');
});
});
sorry for the wall of text.
try to put it this way :
$(document).on('click',"button#save-email", function() {...
instead of
$("button#save-email").on('click', function()
using the second one won't work, because when it is run, $("button#save-email"), doesn't exist yet.
The problem is that the first handler is the only one attached in script.
Your javascript code is executed when the page is ready.
At that moment only the first handler is attached because there is not yet an element button#save-email. When you click save, it is the first handler that is executed again, not the one think !
Why don't you create two distinct buttons and show one or the other ?
<table>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
<tr>
<td class="email">myemail#domain.com</td>
<td>
<button class="btn-edit">Edit</button>
<button class="btn-save" style="display:none">Save</button>
</td>
</tr>
</table>
Javascript
// listen for email edit button click
$('.btn-edit').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get email inline to this edit button
var email = $this.parent().siblings('td.email').html();
// change button from edit to save
$parentRow.find('.btn-edit').hide();
$parentRow.find('.btn-save').show();
// change email display to input field
$(this)
.parent()
.siblings('td.email')
.html('<input type="text" id="user-email" value="'+email+'" />');
});
// listen for email save button click
$('.btn-save').on('click', function() {
var $this = $(this),
$parentRow = $this.closest('tr');
// get new email inline to this save button
var newEmail = $(this).parent().siblings('td.email').find('#user-email').val();
// change input field back to display
$(this).parent().siblings('td.email').html(newEmail);
// change button from save to edit
$parentRow.find('.btn-edit').show();
$parentRow.find('.btn-save').hide();
});
DEMO
Take a look at KnockoutJS, which utilizes nice Bindings helping you to do things like that much easier. Here is an example of an editable grid with KnockoutJS
KnockoutJS Editable Data example
Neat & Works
<table>
<tr>
<td>some text</td>
<td><input type='button' value='edit' id='btn'/></td>
</tr>
</table>
$(document).ready(function() {
$("#btn").click(function() {
var $btn=$(this);
var opn= $btn.val()
switch(opn){
case 'edit':
var $td=$(this).parent().parent().find('td:first');
var email=$td.html();
$td.html("").append('<input type="text" value="'+email+'">');
$btn.val("save");
break;
case 'save':
var $input=$(this).parent().parent().find('td:first input');
var email=$input.val();
$input.parent().html(email);
$btn.val("edit");
break;
}
});
});
http://jsfiddle.net/h55rc/

Categories