Getting the value of attribute data-* in an inline function - javascript

I have a data attribute data-niq which i am using to store some data. I want to pass the data in *-niq to a function as a second parameter to a function.
This is the code
<button onClick="editevent(this.id,this.id.getAttribute('data-niq'));" id="mid" data-niq="niq" class="mr edit btn btn-success pull-right"> Edit</button>
<script>
function editevent(clicked_id,attri_bute){
console.log('clicked id',clicked_id);
console.log('data-niq',attri_bute);
}
</script>
and the link https://jsfiddle.net/codebreaker87/zob8dm4z/8/
When i run the code i get TypeError: this.id.getAttribute is not a function
How can i pass the data-niq value in the inline function that i am calling?.

Few things here
Never mix your mark up with javascript
Try to bind events in javascript end.
check the following snippet.
window.onload = function() {
var mid = document.getElementById("mid");
mid.addEventListener('click', function() {
editevent(this);
})
}
function editevent(thisObj) {
var id = thisObj.getAttribute('id');
var dataniq = thisObj.getAttribute('data-niq');
alert(id);
alert(dataniq);
}
<button id="mid" data-niq="niq" class="mr edit btn btn-success pull-right">Edit</button>
Hope it helps

you have added this.id.getAttribute('data-niq');
remove id
this.getAttribute('data-niq')

Related

Uncaught ReferenceError: addToCart is not defined javascript

i am using javascript onclick function to make a function but it returns an error
Uncaught ReferenceError: addToCart is not defined i don't know why
here is my code
my javascript code
function addToCart(){
var productname = $('pname').text();
var productid = $('productid').text();
var color = $('#color option:selected').text();
var color = $('#size option:selected').text();
var quantity = $('#qty').val();
$.ajax({
type: "POST",
dataType: 'json',
data:{
color:color,
size:size,
quantity:quantity,
productname:productname,
},
url: "cart/data/store"+productid,
success:function(data)
console.log(data);
})
and my onclick input
<input type="submit" class="btn btn-primary" onclick="addToCart()" value="add to cart">
You did onclick="addToCart()" which immediately executed the function you should onclick="addToCart".
This is probably happening because the browser isn't properly loading your function. I would try adding a console.log above and outside of your function definition to make sure it's being loaded.
More generally, if you're using jQuery, you probably want to attach that addToCart onclick handler in Javascript rather than in HTML. See this question for more details: Add onclick event to button after document is ready with JS/JQuery selecting by class
In the case of everything is okay then what you can do is insted of onclick in html
<input type="submit" class="btn btn-primary" id="cart-btn" value="add to cart">
Script:
$(document).ready(function(){
function addToCart(){
//function definition
}
$("#cart-btn").click(addToCart);
});
I think your addToCart function is either not loading or not defined in the global scope!
Example 1 (Function defined in global scope)
function hi() {
alert("hi");
}
<button onclick="hi()">Click Me</button>
Example 2 (onClick function not defined in global scope)
(() => {
function hi() {
alert("hi");
}
})()
<button onclick="hi()">Click Me</button>

How to increment the name attribute array using javascript function

I want to increment the value of the name attribute whenever the function is called. Below I have added all the code through which I add new text boxes using jQuery clone function. Hope now everything is clear.
function addQuestion(){
var question = jQuery('#question-template').clone();
question.css("display","block").removeAttr('id');
jQuery('#questions').append(question);
}
function renameQuestions(){
jQuery('.question-box').each(function(i,v){
jQuery(this).find('.question_id').html(i);
});
}
jQuery('#add-question').on('click', function(e) {
e.preventDefault();
addQuestion();
renameQuestions();
});
jQuery(document).on('click','.del-question', function(e)
{
e.preventDefault();
jQuery(this).closest('.question-box').remove();
renameQuestions();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="quiz[0][english][ques_title]" class="ques_title" placeholder="Enter question title" value="">
<textarea name="quiz[0][english][ques_desc]" class="ques_desc" rows="4" placeholder="Explaination here...."></textarea>
<a id="add-question" class="button" href="#">Add</a>
<a class="del-question button" href="#" data-id="1">Remove</a>
I want to increment the value quiz[0], whenever the add-question button is clicked, I tried using PHP adding a PHP variable in the JS function. But then I got to know it will not work because one is server side and other is client side scripting.
Demo: http://jsfiddle.net/GCu2D/5163/
JS:
function renameQuestion() {
var question = $(".question-box:last");
var total_question = parseInt((".question-box input:first").attr("name").replace( /^\D+/g, ''))+1;
question.find("input").each(function() {
var elem = $(this);
elem.attr("name", elem.attr("name").replace(/[0-9]/g, total_question));
});
}
This should solve your issue.

Action always going to Index using submit()

In my view, I'm using a function, submitForm(action) to submit the form on button click. This is one of many buttons that will use this function. The action parameter will indicate which controller method to use.
The function seems to generate the correct Action attribute (the path is correct in the console), but it is always directed to the Index method rather than the action parameter.
The button:
<input type="button" value="Save Only" id="save" onclick="submitForm('SaveOnly')" />
The function:
function submitForm(action) {
var $form = $("#myForm");
$form.action = ("/Area/MyController/" + action);
$form.submit();
}
You're not accessing the 'action' attribute of the form itself, but to the jQuery selector result, in order for your code to work, you need to access the DOM element from inside the selector with $form[0].
I recommend to stick to jQuery, you're already using it!. Below is a working code with jQuery selectors.
<form id="myForm"></form>
<input type="button" value="Save Only" id="save" data-action="saveOnly" />
<script>
$('#save').click(function(){
var action = $(this).data('action');
var $form = $("#myForm");
$form.attr('action', "www.google.com?q=" + action);
$form.attr('method', 'GET');
$form.submit();
});
</script>

Show submit when checkbox is checked loop

I've got a page in wordpress that displays around 20 poll questions (using WP-polls).
I'm using a snippet to display the submit button for each poll once an answer has been checked. Thing is, with this snippet I have to copy paste it about 20 times, because of that I some kind of loop.
This is the current code I'm using
$(document).ready(function() {
var $submit = $("#btn-7").hide(),
$cbs = $('input[name="poll_7"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-6").hide(),
$cbs = $('input[name="poll_6"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-5").hide(),
$cbs = $('input[name="poll_5"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
As you can see what changes is the "btn_number" ID and "poll_number". This goes on for another 20 snippets. How can I make this dynamic?
jQuery allows you to use wildcards, for example:
var $submit = $("#btn-*").hide(),
$cbs = $('input[name="poll_*"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
Edit: I see the wildcard selectors isn't supported by jquery anymore (as above example) you might want to look at: http://james.padolsey.com/javascript/regex-selector-for-jquery/ which gives you the ability to use regex to define the selectors for all btn's and code for it once
You can use the starts with selector on the ID and name attributes, to dynamically access the number. The change event is more appropriate than the click event for checkboxes.
Demo
$('[id^="btn-"]').hide();
$('input[name^="poll_"]').change(function(){
var number = this.name.replace('poll_', '');
$('#btn-' + number).toggle( $(this).is(":checked") );
});
It would be better to use data-* attributes to link the buttons and checkboxes, or nest them in an element that has the ID. Parsing the number out of the ID attribute isn't the cleanest way.
You don't have to repeat the same code for 20 times just for getting different button ids. you can make it dynamic. checkout this simple example
$("#submit").click(
function()
{
for(i=1;i<=5;i++)
{
msg = $("#btn-"+i).val()
alert(msg)
}
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="button" id="btn-1" value="button1">
<input type="button" id="btn-2" value="button2">
<input type="button" id="btn-3" value="button3">
<input type="button" id="btn-4" value="button4">
<input type="button" id="btn-5" value="button5">
<p>
<input type="button" value="submit" id="submit">
$(document).ready(function(){
for(var i=1;i<=20;i++){
var submit = $("#btn-"+i).hide(),
cbs = $('input[name="poll_'+i+'"]').click(function(){
submit.toggle($this.is(":checked"));
});
}
});

JQuery get formaction and formmethod

I have the a like this one
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button" onclick="popisgolubova_radiobutton(this)">
<input name="rodovnik" type="button" formaction="rodovnik.php" formmethod="post" formtarget="_blank" value="rodovnik" class="button" onclick="popisgolubova_radiobutton()">
<input name="podaci" type="button" value="poodaci" formaction="podaciogolubu.php" formmethod="post" formtarget="_blank" class="button" onclick="popisgolubova_radiobutton()">
</form>
and javascript
function popisgolubova_radiobutton(element)
{
alert($(element).find("[formaction]").val());
var popisgolubova_radiobutton=$("input[name=RadioGroup1]").is(":checked");
if(popisgolubova_radiobutton==false)
{
alert("nop");
}
else
{
$("form#popisgolubova_form").submit();
}
}
First I'm checking if any checkbox is checked or not and if it is the I can submit the form. But the problem is formaction, formmethod and formtarget. how to get them and submit them
To get the action or method attributes of a form you can try something like below:
$(function() {
var action = $("#formid").attr('action'),
method = $("#formid").attr('method');
});
Hope this helps to get an idea to solve ur problem
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button postForm"/>
</form>
$(document).on('click', '.postForm', function () {
$('#popisgolubova_form').attr('action', $(this).attr('formaction'));
$('#popisgolubova_form').attr('method', $(this).attr('formmethod'));
$('#popisgolubova_form').attr('formtarget', $(this).attr('formtarget'));
});
So the question is talking about the unfortunately named
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction
...which is a way to override
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action
per clicking a properly set up submit button. The place you want to check this is upon submit - when you're sure things are actually being submitted.
The button you used to submit is stored as :focus - this does not seem to be otherwise stored in the event object at the moment.
$('form').on("submit", function(event) {
if( $(':focus').is('[formaction]') ) {
console.warn($(':focus').attr('formaction'));
}
if( $(':focus').is('[formtarget]') ) {
console.warn($(':focus').attr('formtarget'));
}
});
if( $(':focus').is('[formaction]') ) {
console.log($(':focus').attr('formaction'));
}
I had this problem and after searching the web I couldn't find a proper answer. Finally, I realized it's so simple.
When you add an event on form.submit you have an event argument that contains e.originalEvent.submitter, just use it as follows:
$('form').submit(function(e){
var url = form.attr('action');
if (e.originalEvent.submitter) {
var frmAction = $(e.originalEvent.submitter).attr('formaction');
if (frmAction)
url = frmAction;
}
,.....
});
You can use the samething for the formmethod as well.

Categories

Resources