how to store & read arbitrary url inside Input field - javascript

i have the following inside my asp.net mvc view:-
<input type="submit" id="addswitch" data-targeturl="#Url.Action("showSwitches","Rack")" class="btn btn-small btn-primary" value="Add">
the idea is that i need to store the realted URL insdie an arbitrary value which i name it data-targeturl.
then inside my script , which will fire when the user clicks on the above input field as follow:-
$('body').on("click", "#addserver,#addsd,#addfirewall,#addrouter,#addswitch", function () {
$("#showAddDialog").dialog({
title: "Add Exsisting " + dialogtitle,
width: 'auto', // overcomes width:'auto' and maxWidth bug
maxWidth: 600,
height: 'auto',
modal: true,
fluid: true, //new option
resizable: false
});
var URL = this.data-targeturl;
but currently i am getting the following error:-
ReferenceError: targeturl is not defined
var URL = this.data-targeturl;

You need to use .data() or dataset
var URL = $(this).data("targeturl");
//OR
//var URL = this.dataset.targeturl;
instead of
var URL = this.data-targeturl

Related

Laravel js DataTable: how do I assign a value from js back to the .blade?

I have these rows:
each row is being outputted by the DataTable plugin within app.js
my target is this particular value, ${row.category_id}
let TABLE = $('#categoryList').DataTable({
{ data: 'id', name: 'id', width: '10%', orderable: false, searchable: false,
render: (data, type, row) =>{
let html = "";
if(row.category_name && row.category_name.toUpperCase() !== "GENERAL"){
html += `<ul class="list-inline no-margin">`;
html += `<li class="list-inline-item">
<button type="button" value="${row.category_id}" class="edit_category btn btn-outline-secondary"><i class="fas fa-edit" aria-hidden="true"></i> Edit</button>
</li>`;
html += `</ul>`;
}
return html;
}
}
});
now I have this blade file, index.blade.php that is connected to app.js using:
<script src="{{asset('/modules/bbr-category-configuration/js/app.js')}}"></script>
What I need to resolve is the constant below:
#section('scripts')
<script type="text/javascript">
const SELECTED_CATEGORY_ID = 1;
</script>
#endsection
by default it is set as 1, but this needs to changed each time the 'Edit' button is clicked (refer to the screenshot). Once the button is clicked, I need to get ${row.category_id} and assign it to the const SELECTED_CATEGORY_ID. What is the correct way of doing this?
TLDR: how do I pass a value from .js back to .blade.php?
What I tried:
my first obstacle is to get the value from ${row.category_id} on click, but here is where I got stuck
$(document).on('click', '.edit_category', function () {
console.log(${row.category_id});
});
I cannot console.log (to test if I got the correct variable) outside the DataTable because it cannot be read, or do it inside toe columns because it is not the right syntax.
please feel free to ask for any clarifications.
First of all, if your variable's data will change during the process then it is not const it should be declared as let. You should know the difference between var let and const.
And you can use data-* attributes in the edit button so you can easily fetch the category_id when that button is clicked eg:
<button type="button" data-category=`${row.category_id}`class="edit_category">Edit</button>
Then on click event, you can get that data using
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).data('category');
});
You can fetch the value attribute of the button too using jquery. But generally, I don't use that. Or I haven't seen much usage of that too. You can try it like this too
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).value;
});

Replacing two variables after filling a form

I'm not much of a Javascript expert, but sometimes I need to turn to it.
I have a script which allows the user to choose two dates (from and to) to create a report.
<div onmouseover="myFunction()">
<input id="id_from_date" name="from_date" type="text">
<input id="id_to_date" name="to_date" type="text">
</div>
<script>
function myFunction() {
$('#id_from_date').datetimepicker({
format: 'd-m-Y',
lang: 'pl',
pickTime: false,
timepicker: false,
weeks: true,
dayOfWeekStart: 1,
closeOnDateSelect: true
});
$('#id_to_date').datetimepicker({
format: 'd-m-Y',
lang: 'pl',
pickTime: false,
timepicker: false,
weeks: true,
dayOfWeekStart: 1,
closeOnDateSelect: true
});
var from = document.getElementById("id_from_date").value;
var to = document.getElementById("id_to_date").value;
var url = '{% url 'logistyka_tabela_brakow.views.report_from_to' '11-11-1111' '12-12-1212' %}';
document.getElementById("link").setAttribute("href", url.replace(/11-11-1111/, from), url.replace(/12-12-1212/, to))
}
</script>
<a id="link" type="button" class="btn btn-success">go!</a>
I'm at the end of my tether here. The code replaces the first variable, id_from_date, with the date a user chooses. Unfortunately, it ignores the second variable, id_to_date. Can anyone please give me a hint why it happens so?
I cannot leave var url withour any initial values, because the application crashes without anything given while opening the view.
The whole project is created in Django and the view for the report is:
def report_from_to(request, from_date, to_date):
from datetime import datetime
strfrom = datetime.strptime(from_date, "%d-%m-%Y")
strto = datetime.strptime(to_date, "%d-%m-%Y")
report = Braki.objects.filter(Q(date__gte=strfrom), Q(date__lte=strto))
return render(request, 'logistyka_tabela_brakow/report_from_to.html', {'report': report})
the form:
class ReportForm(forms.Form):
from_date = forms.DateField()
to_date = forms.DateField()
fields = '__all__'
the url is obviously:
url(r'report_from_to/(?P<from_date>[0-9]{2}-[0-9]{2}-[0-9]{4})/(?P<to_date>[0-9]{2}-[0-9]{2}-[0-9]{4})',
'logistyka_tabela_brakow.views.report_from_to', name='report_from_to'),
The syntax of setAttribute is
element.setAttribute(name, value);
You are calling it with 3 arguments, so the third one gets ignored.
document.getElementById("link")
.setAttribute("href",
url.replace(/11-11-1111/, from),
url.replace(/12-12-1212/, to)
);
This should do it
var url = '{% url 'logistyka_tabela_brakow.views.report_from_to' '11-11-1111' '12-12-1212' %}';
url = url.replace(/11-11-1111/, from);
url = url.replace(/12-12-1212/, to);
document.getElementById("link").setAttribute("href", url);

bootstrap popover update content

how do you update the content of bootstrap popover after ajax success, I specifically need to change the value of the input field that I have but once I close the popover and click on it, the original value of the input field shows up? can someone help me out?
<button class="btn btn-primary edit" data-content='<input type="text" id="name" value="some value">
<button class="btn btn-primary save">Save</button>'>Edit</button>
JavaScript:
$('.edit').popover({
placement: 'left',
html: true,
});
$('body').on("click", ".save", function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "test.php",
data: {
name: name
},
cache: false,
success: function(response) {
if (response.indexOf("success") != -1) {
$('#name').val(name);
$('.edit').popover('hide').next('.popover').remove();
}
}
});
});
after the data is saved the popover is closed and when I click edit again the old value shows in the input box.
Please find enclosed a working demo of a popover that will be updated with the response from an ajax request.
I've removed your request parameters just for the demo to be able to do the request with mocky.io.
The trick was to use .attr('value', text) instead of .val(text). I'm not exactly sure what's going on here. Maybe someone can explain why that's different.
But with attr it changes the popover and it works.
Another thing that is required is to recreate the popover. I also wanted to destroy the first popover but that doesn't work. So I created the same popover again.
You can also find the same code here at jsFiddle.
There is a bug in the code here at SO. If you get the data from the server and then close the popover, the data will be reset to initial value.
Don't know what's wrong, because it works at jsFiddle with-out that bug.
Update 04.12.2014:
I've improved the code a bit. Now there is a close button in the popover and the data is stored so the data from server is still available when the popover is re-opened.
The bug mentioned above was probably not a SO issue, it was because the data from server was not properly stored. That is also fixed now.
I've also removed some not needed script tags in the demo because tooltip and popover are already included in bootstrap 3.
Update 05.12.2014:
I have another improvement to the code.
The line $(this).parent().find('.close').click(...) is not working like I wanted it. I wanted to add the handler only to the close button of the current popover. But it adds it to all elements with class .close.
Because $(this).parent() is the body element. I think it is better to do it like this:
var current_popover = '#' + $(e.target).attr('aria-describedby');
var $cur_pop = $(current_popover);
$cur_pop.find('.close').click({});
With aria-describedby you'll get the id of the current popover and then you can find the close button of that popover.
$(function () {
var editData = 'new value';
var doPopover = function (item, text) {
$('#name').attr('value',text); // use set attr and not val()
//$('#name').val(text); //<<<< not working here doesn't set DOM properly
var $pop = $(item);
$pop.popover({
placement: 'right',
title: 'edit <a class="close" href="#">×</a>',
trigger: 'click',
html: true,
content: function () {
return $('#popup-content').html();
}
}).on('shown.bs.popover', function(e) {
// console.log('triggered');
// 'aria-describedby' is the id of the current popover
var current_popover = '#' + $(e.target).attr('aria-describedby');
var $cur_pop = $(current_popover);
$cur_pop.find('.close').click(function(){
//console.log('close triggered');
$pop.popover('hide');
});
});
return $pop;
};
// enable popover
doPopover('.edit', editData);
// edit button click handler to show popover
$('.edit').click(function() {
doPopover('.edit', editData);
});
$('body').on("click", ".save", function (e) {
e.preventDefault();
var name = $('#name').val();
//console.log($popover);
$.ajax({
type: "GET", //"POST",
url: "http://www.mocky.io/v2/547f86501713955b0a8ed4da", //"test.php",
data: {
//name: name
},
cache: false,
success: function (response) {
editData = response.data;
doPopover('.edit', editData);
console.log('response: ', editData);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<button class="btn btn-primary edit" data-html="true" data-toggle="popover" class="edit" data-title="Edit">Edit</button>
<div id="popup-content" class="hide">
<input type="text" id="name" value="some value" />
<button class="btn btn-primary save">Save</button>
</div>

adding element with duplicate id 'FileULoader' FileUploader

createContent : function(oController) {
var oFileUploader = new sap.ui.commons.FileUploader({
id: "FileULoader",
//uploadUrl : "UploadFileServelet", // URL to submit the form to
name: "simpleUploader", // name of the input type=file element within the form
// uploadOnChange: true, // immediately upload the file after selection
buttonOnly: false,
buttonText: "Upload"
}).addStyleClass("downloadBtn");
oFileUploader.attachUploadComplete(oController.doFileLoadComplete);
//var uploadBtn=new sap.ui.commons.buttons{this.creatId("upLoadFile"),}
var oMatrix = new sap.ui.commons.layout.MatrixLayout({
layoutFixed : true,
width : '400px',
columns : 1 });
var text = new sap.ui.commons.TextView({text:"Confirm that the data will be wiped out once you upload new data file."});
oMatrix.createRow(oFileUploader);
oMatrix.createRow(text);
var oDialog = new sap.ui.commons.Dialog({
title:"FileUpload",
resizable:false,
modal:true,
showCloseButton:true,
contentBorderDesign:"Box",
content:[
oMatrix
],
buttons:[
new sap.ui.commons.Button({text:"Confirm", tooltip:"Confirm",press:function(e){oController.doFileUpload();oDialog.close();}}),
new sap.ui.commons.Button({text:"Cancel", tooltip:"Cancle",press:function(e){oDialog.close();}}),
]
});
return oDialog;
i used in two views . when i call the fileUploader the error turns out。
i have to use the id to identify the fileloder controller. to get the input file information .
update:
_uploadCourse:function(){
if (!this.dialogUploadFile) {
this.dialogUploadFile = sap.ui.jsfragment("courseUP",
"adminView.dialogUploadFile", this);
}
this.dialogUploadFile.open();
},
_uploadCourse : function() {
if (!this.dialogUploadFile) {
this.dialogUploadFile = sap.ui.jsfragment("certiUploadFile",
"adminView.dialogUploadFile", this);
}
this.dialogUploadFile.open();
},
this is how i use the fragment. but is still go wrong with thew same error;
#Allen Zhang
You mentioned you used the code in two views. You can't create a dialog twice with the same id of Fileupload control. Use different id for different views.
Updated:
Define id for your fragment usage:
<core:Fragment id="myFrag" fragmentName='my.frag' type='JS' />
Define fileupload id by calling createId:
var oFileUploader = new sap.ui.commons.FileUploader({
id: this.createId("FileULoader"),
//uploadUrl : "UploadFileServelet", // URL to submit the form to
name: "simpleUploader", // name of the input type=file element within the form
// uploadOnChange: true, // immediately upload the file after selection
buttonOnly: false,
buttonText: "Upload"
}).addStyleClass("downloadBtn");
Also see my answers about fragment usage and get control inside fragment.
Is an option that you do not use id for the file uploader control, and do it like this?
createContent : function(oController) {
this.oFileUploader = new sap.ui.commons.FileUploader({
To access it, you do
view.oFileUploader
where view is the javascript handle of one of your two views.
-D

Changing the title of a dynamically generated dialog

I'm using tinymce with my own File Browser:
file_browser_callback: function(field_name, url, type, win)
{
tinyMCE.activeEditor.windowManager.open({
title: 'My Title',
url : 'file_browser.html',
}
I wish to dynamically change the title, "My Title" of the dialog using javascript from within the file_browser.html iframe.
The html generated by tinymce looks something like this:
<div id="mceu_76-head" class="mce-window-head"><div id="mceu_76-title" class="mce-title">My title</div></div>
<div id="mceu_76-body" class="mce-container-body mce-abs-layout"><iframe src="file_browser.html" tabindex="-1">
Obviously I can't use getElementById("mceu_76-head") since this is dynamically generated and there are other dialogs whose Title I don't wish to change. What should I do?
windowManager.open returns window settings which contains the id.
var win = tinyMCE.activeEditor.windowManager.open({
title: 'My Title',
url : 'file_browser.html',
...
});
document.getElementById(win._id + '-title').innerHTML = 'New Title';
It works but I'm not sure it is right way.

Categories