JQuery Button Data Returning As Null? - javascript

I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.
HTML BUTTON
<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>
JS FUNCTION(W/ JQUERY)
function whoIsRdns(thisButton){
//Enable jQuery properties from the param of the HTML object
var btn = $(thisButton);
var test = btn.data('hi');
console.log('Value is ' + test);
}
Why would test return as null?

Shouldn't var btn = $("thisButton"); be var btn = $(thisButton); (without quotes)

Just a typo
$("thisButton") !== $(thisButton);
drop the quotes so you are not looking for an element with a tag name thisButton
var btn = $("thisButton");
needs to be
var btn = $(thisButton);

Related

Find and Click button with JS

I'm trying to use a chrome extension (shortkeys) to create shortcut keys that can press buttons within our warehouse management system (so they can be matched to barcodes).
One of the buttons has no ID, and once it has been clicked the button innertext changes. Ideally I'd like the shortcut to work on either version of the button
It is either
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
or
<a class="btn btn-success" href="/Order/OrderDocumentP/15467" target="_blank">Print Label</a>
I then have another button to be assigned to a different shortcut key
<a class="btn btn-success" href="/Picking/DespatchOrder?OrderId=13413">Despatch</a>
But I'm sure once I've figured out the first one the next will be easier :)
Any help greatly appreciated, I've been through a number of other questions that are similar but not quite what I'm after and my JS knowledge is pretty rubbish
Learn CSS a bit and use https://developer.mozilla.org/ru/docs/Web/API/Document/querySelector
Your extensions probaply supports that
// cuz I don't like to type long "document.querySelector"
q = sel => document.querySelector(sel)
qq = sel => document.querySelectorAll(sel)
function clickOnly(sel) {
let list = qq(sel);
if (list.length == 1) list[0].click();
else alert('element "'+sel+'" is not unique!');
}
// handles *any* keypress
onkeypress = function (event) {
if (event.target.tagName == "INPUT") return; // noop on input focused
if (event.target.tagName == "TEXTAREA") return; // noop on input focused
console.log(event.code); // to see what the key is
let rawCode = event.code; // keyboard key, `KeyM` for M, `Digit7` for 7, `Slash` for /
let code = rawCode; // make CtrlAltShiftKeyM
if (event.shiftKey) code = 'Shift' + code;
if (event.altKey) code = 'Alt' + code;
if (event.ctrlKey) code = 'Ctrl' + code;
if (!kds[event.code]) return;
event.preventDefault(); // prevent CtrlKeyM browser handler for bookmarks or whatever
kds[event.code](event);
}
kds = {}
// it's a function so starts with `() => `
kds.KeyM = () => alert('it works!')
// a is for <a>, [href^=] is for href starts with
kds.ShiftKeyM = () => clickOnly('a[href^="/Order/OrderDocumentP/]')
// , is for one of multiple selectors
kds.CtrlKeyM = () => clickOnly('input[value="Create Shipment"], a[href^="/Order/OrderDocumentP/]')
This is a simple script on getting a button by class name and clicking it. I think this is what you are looking for, if not let me know I will rewrite it.
EDIT: I added a loop that will click all buttons or links found with the class name btn-success
I've inserted a second function so people looking for a solution by classname can also still find the first one. AutoClickBtnByValue() will click the button with inner text "click me now".
function AutoClickBtn() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
button[i].click();
console.log('Success! Clicked button' + i);
}
}
setInterval(AutoClickBtn, 2000);
/* Click button by innerHTML text */
function AutoClickBtnByValue() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
if (button[i].innerHTML.indexOf('click me now') > -1) {
button[i].click();
console.log('Success! Clicked button' + i + ' with value: "click me now" ');
}
}
}
setInterval(AutoClickBtnByValue, 2000);
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
<a class="btn btn-success" href="#" target="_blank">Print Label</a>
<a class="btn btn-success" href="#">Despatch</a>
<button class="btn-success">click me now</button>

Laravel 7 Ajax Datatables get data update

I have a problem that make me stuck for a couple days.
I use laravel 7 and jax, and yajra datatables and i want to make page edit which show data by id from database.
before this i use popup modal to create and edit data, but for this i want to make another page for create and edit, so i would direct to another page like this
"/pegawai/edit/{{ $p->pegawai_id }}". so when i click button edit there are direct to page edit.
for page create and function delete is ok, but i stuck at edit.
this my controller to get list
public function getList(Request $request){
$data = Cms::all();
$canEdit = Auth::user()->can($this->permissions["edit"]);
$canDelete = Auth::user()->can($this->permissions["delete"]);
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row)use($canEdit,$canDelete){
$btn = '';
$canEdit ? $btn .= "<a href='/console/cms/editData'>
<button
type = 'button'
class = 'btn btn-warning btn-sm'
onclick = 'editData(this)'
idData = '".$row->id."'
title = '".$row->title."'
slug = '".$row->slug."'
meta_title = '".$row->meta_title."'
meta_desc = '".$row->meta_desc."'
description = '".$row->description."'
>Edit</button></a>":'';
$canDelete ? $btn .= '<button
type = "button"
class = "btn btn-danger btn-sm"
onclick = "deleteData(this)"
idData = "'.$row->id.'"
>Delete</button>
':"";
return $btn;
})
->rawColumns(['action'])
->make(true);
}
this function at blade
function editData(attribute){
resetError();
resetForm();
var id = $(attribute).attr('idData');
var title = $(attribute).attr('title');
var slug = $(attribute).attr('slug');
var meta_title = $(attribute).attr('meta_title');
var meta_desc = $(attribute).attr('meta_desc');
var content = $(attribute).attr('description');
tinymce.get("description").setContent(content);
var cms_file = $(attribute).attr('cms_file');
$("#id").val(id);
$("#title").val(title);
$("#slug").val(slug);
$("#meta_title").val(meta_title);
$("#meta_desc").val(meta_desc);
$('#description').val(description);
$('#cms_file').val(cms_file);
}
Use the code below:
$canEdit ? $btn .= "<a href='/pegawai/edit/".rawurlencode($row->id)."' class='btn btn-warning btn-sm'>Edit</a>";
if you are using the jquery, you need to add event delegation from the body because the element is coming from ajax. maybe use
$('body').on('click','.yourBtnClassname',function(e){
});
see this Image

button onclick id change not working in Html using javascript

I wanted to change ID of textarea using onclick button. So I created two buttons across my field. Each on click run a function.
Issue: It just replace my id first time and second time when i click on second button it throws error saying "Uncaught TypeError: Cannot set property 'id' of null at ti_pos_fun (index.html:491)"
HTML code-
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()"></i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()"></i>
</div>
I am trying to use two buttons- example
Now when you click check button- ti runs the onclick function "ti_pos_fun".
Function are as follows
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
Textarea code where these ids are going & their text.
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
You click on button 1 - check button
It gets id and text in textarea
When you click on button 2- uncheck button
It fails
Its not working on 2nd click because you are overwriting the id of that element
//a.id = "ti_neg";
so on 2nd click there is no element with id jsel and below statement will return null and it will not work.
document.getElementById("jsel");
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
//a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('jsel').innerHTML = 'angry';
}
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
//a.id = "ti_pos";
document.getElementById('jsel').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()">1</i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()">2</i>
</div>
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>
That's because the ID isn't jsel anymore you need something like this, if it can't find jsel check for the ID the other function set and visa versa. EDIT: added snip that works.
function ti_pos_fun ()
{
var a = document.getElementById("jsel");
if (a != null){
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}else{
var a = document.getElementById("ti_neg");
a.id = "ti_pos";
document.getElementById('ti_pos').innerHTML = 'hahahahaha';
//$("#ti_pos").text('hahahaha');
}
}
function ti_neg_fun ()
{
var a = document.getElementById("jsel");
if(a != null){
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}else{
var a = document.getElementById("ti_pos");
a.id = "ti_neg";
//$("#ti_neg").text('angry');
document.getElementById('ti_neg').innerHTML = 'angry';
}
}
<div>
<label for="usr">ti:</label> <i class="glyphicon glyphicon-check" onclick="ti_pos_fun()">postitive</i> <i class='glyphicon glyphicon-unchecked' onclick="ti_neg_fun()">negative</i>
</div>
<div class="col-md-10">
<H3> textarea</H3>
<textarea id = "jsel"></textarea>
</div>

how to add attribute name in summernote click to edit

I want to add element attribute name in summernote click to edit
html :
<button id="edit" class="btn btn-primary" onclick="edit()" type="button">Edit 1</button>
<button id="save" class="btn btn-primary" onclick="save()" type="button">Save 2</button>
<div class="click2edit">click2edit</div>
javascript:
var edit = function() {
$('.click2edit').summernote({focus: true});
};
var save = function() {
var makrup = $('.click2edit').summernote('code');
$('.click2edit').summernote('destroy');
};
doc :
http://summernote.org/examples/#click-to-edit
You can do like this. Just find the text area add the name attribute.Hope it work.
var edit = function() {
$('.click2edit').summernote({focus: true});
$('.note-editor.note-frame.panel.panel-default').find('textarea').attr('name','mytextarea');
};
I don't think you need anything fancy here.
Use attr() on summernote selector
$('.summernote').attr('name', 'content');
Here, I assume that $('.summernote') is selector of editor applied.
Example, shows how to get instance of editor
$("#id").on("summernote.init", function(e, layoutInfo) {
// get $editor element
var $editor = layoutInfo.editor();
// add id attribute in $editor element
$editor.attr('id', $(this).attr('id') + "-of-example");
}).summernote(
// summernote options..
);
var edit = function() {
$('.click2edit').summernote({focus: true});
$('.note-editor').find('textarea').attr('name','mytextarea');
};

How to add working dropify inputs dynamically

I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.

Categories

Resources