Button click function not working in jQuery - javascript

So I'm developing a website for a medical clinic and they asked me to add a button beneath every doctor to make an appointment.
this is what i have for the doctors section
for (var i = 0; i < 3; i++) {
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].ficheiro + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" type="button" class="btn btn-primary">Marcar consulta</a>' +
'</div>' +
'</div>' +
'</div>'
);
}
The then code for the click function (that doesn't work):
$('#marcar').click(function() {
var offset = $('#marcacao').offset();
$('html, body').animate({
scrollTop: offset.top-100,
scrollLeft: offset.left
}, 1000);
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(medico[i].especialidade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(medico[i].nome);
console.log('test');
});
This is all inside a $(document).ready(function() {}); and what should do is when i click that button beneath the doctor, should go up to the form and fill the doctor's name and specialty... but it seems it's not working for some reason... this is a copy of other click functions in the code, but they seem to work fine.
HTML form:
<div id="marcacao-consulta" data-target="#marcacao-consulta">
<div class="row">
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="especialidade-marcacao" class="gui-input">
<option id="especialiade-default" value="default">Escolha a especialidade</option>
<?
$query = $dbHandle->prepare("
SELECT `especialidade`
FROM `especialidade`
ORDER BY `especialidade` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["especialidade"]; ?>"><?=$row["especialidade"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-heartbeat"></i></span>
</label>
</div>
</div>
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="corpo-clinico-marcacao" class="gui-input">
<option id="corpo-clinico-default" value="default">Escolha o médico</option>
<?
$query = $dbHandle->prepare("
SELECT `nome`
FROM `medico`
ORDER BY `nome` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["nome"]; ?>"><?=$row["nome"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-user-md"></i></span>
</label>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12">
<div class="section">
<label class="field prepend-icon">
<input id="nome" class="gui-input" type="text" placeholder="Nome Completo">
<span class="field-icon"><i class="fas fa-user"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="email" class="gui-input" type="text" placeholder="Endereço de correio eletrónico">
<span class="field-icon"><i class="fas fa-envelope"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="telefone" class="gui-input" type="text" placeholder="Telefone/Télemovel">
<span class="field-icon"><i class="fas fa-phone-square"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="tipo" class="gui-input" type="text" value="consulta" disabled>
</label>
</div>
</div>
</div>
</div>

You have to add the element and register the event for the element. Here is the fiddle which works for you
https://jsfiddle.net/0q3kpyfv/
Your sample HTML
<div id="get_medicos">
</div>
Sample jquery code
Notice I have added the data-val attribute to the added anchor tag which will help you to get the information and perform the logic based on which button is clicked. you can pass dynamic data to data-val attribute and use it in click event.
$(document).ready(function() {
var sampleString = "";
var medico = [{'especialidade':'speciality 0','nome':'Doctor 0'},{'especialidade':'speciality 1','nome':'Doctor 1'},{'especialidade':'speciality 2','nome':'Doctor 2'}]
for (var i = 0; i < 3; i++) {
var doctorData = medico[i];
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].especialidade + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" data-doctor-especialiadade="'+medico[i].especialidade+'" data-doctor-nome="'+medico[i].nome+'" type="button" class="btn btn-primary">Marcar consulta'+i+'</a>' +
'</div>' +
'</div>' +
'</div>'
);
};
$('#get_medicos').on('click','a',function(event){
var elementClicked = event.target;
var doctorEspecialiadade = $(elementClicked).data('doctor-especialiadade');
var doctorName = $(elementClicked).data('doctor-nome');
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(doctorEspecialiadade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(doctorName);
})
});

if you create the button after your event, you could have problem so, use the delegate version of click:
$('div').on('click', 'a', (function()....
and better put an id on the ancestor div:
'<div class="text-box white padding-3" id="mydiv"'
:
$('#mydiv').on('click', 'a', (function()....
another thing, with the loop you will have same id more time in your html??its no good.
so you'll have to rebuild your program logic...and bind the event with the right button (use a common class) it will be better than an id

If you bind the event to the parent element, and filter by the children, you can listen to any new elements that are added, doesn't matter how many.
<div class="container"></div>
<button class="js-add-new">Add new</button>
const $addNew = $('.js-add-new')
const $container = $('.container')
let count = 0
$addNew.on("click", () => {
count += 1
$container.append(`
<div>
<button>log me ${count}</button>
</div>
`)
})
$container.on("click", "button", (event) => {
console.log(event.currentTarget)
})
A working example: https://codepen.io/alexmccabe/pen/jOrXZxj?editors=1111

The button click is working. Here is a fiddle showing it does:
https://jsfiddle.net/bradberkobien/qL4m10y6/3/
There must be an issue with the code that comes before the console.log("test") line within the click. I would use the debugger to help you with that.

Related

Jquery : Find only one nearest matching element

i am adding form fields dynamically using Below code
$(document).ready(function () {
var add_fields = "" +
"<div class='col-md-3 form-group pull-right'>" +
"<label>Please select a field type</label>" +
"<select name='add_fields' class='form-control' id='add_fields'>" +
"<option value=''>Please Select a value</option>" +
"<option value='text'>Text Field</option>" +
"<option value='select'>Select List</option>" +
"<option value='radio'>Radio Buttons</option>" +
"<option value='checkboxes'> Checkboxes</option>" +
"<option value='file'> File Upload</option>" +
"</select></div>";
var text_field_append= "" +
"<div class='row'>" +
"<div class='col-md-3 '>" +
"<div class='form-group'>" +
"<label>Add Field Label</label>" +
"<input type='text' name='textfield_label' class='form-control'>" +
"</div>" +
"</div>" +
"<div class='col-md-3'> " +
"<label></label><input type='text' placeholder='' name='' class='form-control field' disabled >" +
"</div>" +
"</div>";
$('#add_form').on('click',function (e) {
$('#form_holder').append(add_fields);
$('#add_fields').on('change',function () {
if($(this).val()=='text'){
$('#form_holder').append(text_field_append);
var nearest_field= $("[name='textfield_label']").closest('.row').find('.field');
$("[name='textfield_label']").on('input',function(e){
$(nearest_field).attr("placeholder", $(this).val());
var field_name =$(this).val().replace(/ /g,"_");
$(nearest_field).attr("name", field_name);
});
}
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
<h1>Please use Following wizard to generate your form </h1>
<p>Click on Add Fields to get started </p>
<a id="add_form" class="btn btn-primary pull-right">Add Fields</a>
</div>
<form id="myform">
<div id="form_holder">
</div>
</form>
now upon adding a text field i am selecting nearest added element as below:
var nearest_field= $("[name='textfield_label']").closest('.row').find('.field');
Problem with this is i want only latest added(nearest) element to be selected while it selects all the elements, Can someone please advise how can i fix it
The issue is partly due to the repeated id attributes in the dynamic content, which need to be replaced with common class attributes, and also with the nested event handlers.
To both fix the issue and improve the logic, remove all the HTML from the JS and place it within 'templates' in the HTML. Your JS should ideally contain no HTML at all as it's a violation of the Separation of Concerns principle
From there you can use delegated event handlers, bound at runtime, to handle the events on all dynamic elements. These event handlers can use DOM traversal to relate the 'label' to the relevant 'placeholder'.
Finally, note that the template for the field types uses a pattern whereby the first part of its id matches the value of the option used to append it. This way the code is extensible, and your logic can be simplified.
Try this:
jQuery($ => {
let $add_form = $('#add_form');
let $form_holder = $('#form_holder');
let add_fields = $('#fields').html();
$add_form.on('click', function(e) {
$form_holder.append(add_fields);
});
$form_holder.on('change', '.add_fields', e => {
let fieldHtml = $(`#${e.target.value}_field`).html();
$form_holder.append(fieldHtml);
});
$form_holder.on('input', '.text-field-label', e => {
let $label = $(e.target);
let labelValue = $label.val();
let $placeholder = $label.closest('.row').find('.text-field');
$placeholder.prop({
placeholder: labelValue,
name: labelValue,
value: labelValue.replace(/ /g, '_')
});
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
<h1>Please use Following wizard to generate your form </h1>
<p>Click on Add form to get started </p>
<a id="add_form" class="btn btn-primary pull-right">Add Form</a>
</div>
<form id="myform">
<div id="form_holder"></div>
</form>
<script type="text/html" id="fields">
<div class="col-md-3 form-group pull-right"><label>Please select a field type</label>
<select name="add_fields" class="form-control add_fields">
<option value="">Please Select a value</option>
<option value="text">Text Field</option>
<option value="select">Select List</option>
<option value="radio">Radio Buttons</option>
<option value="checkboxes">Checkboxes</option>
<option value="file">File Upload</option>
</select>
</div>
</script>
<script type="text/html" id="text_field">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Add Field Label</label>
<input type="text" name="textfield_label" class="form-control text-field-label" />
</div>
</div>
<div class="col-md-3">
<label></label>
<input type="text" placeholder="" name="" class="form-control text-field" disabled />
</div>
</div>
</script>

How to use input value assigned by javascript onclick in a php form post

i have a form with two buttons, two datepickers and one hidden input. if the oneway button is clicked the return datepicker becomes hidden and the value of the input is changed to oneway. clicking the return button reverts the process and and the value of the input is changed to return.
<script>
$(document).ready(function() {
$("label[name='oneway']").on("click", function(){
sessionStorage.setItem("btnActive", "oneway");
$(".returnpicker").hide();
$("label[name='return']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "oneway";
});
$("label[name='return']").on("click", function(){
sessionStorage.setItem("btnActive", "return");
$(".returnpicker").show();
$("label[name='oneway']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "return";
});
let sessionState = sessionStorage.getItem("btnActive");
if( sessionState == "oneway") {
$(".returnpicker").hide();
$("label[name='return']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "oneway";
} else {
sessionStorage.setItem("btnActive", "return");
$(".returnpicker").show();
$("label[name='oneway']").removeClass('active');
$(this).addClass('active');
document.getElementById('hiddeninput').value = "return";
}
});
</script>
My html looks like this
<form method="post" action="">
<input type="hidden" id="hiddeninput" name="hiddeninput">
<div class="form-row">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label for="oneway" class="btn btn-default " name="oneway">One way</label>
<label for="return" class="btn btn-default " name="return">Return</label>
</div>
<div class="form-group col-lg-3 departure">
<label for="OnewayDatepicker">Departure Date</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="date_added" type="text" name="OnewayDatepicker"class="form-control" value="<?php echo isset($_POST['OnewayDatepicker']) ? $_POST['OnewayDatepicker'] : '' ?>">
</div>
<div class="mb-3">
<?php if (isset($OnewayDatepicker_err )) echo '<p class="text-danger"><small>' . $OnewayDatepicker_err . ' </small></p>'; ?>
</div>
</div>
<div class="form-group col-lg-3 arrival">
<label for="ReturnDatepicker">Arrival Date</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="date_modified" type="text" name="RetunDatepicker"class="form-control" value="<?php echo isset($_POST['RetunDatepicker']) ? $_POST['RetunDatepicker'] : '' ?>">
</div>
<div class="mb-3">
<?php if (isset($ReturnDatepicker_err )) echo '<p class="text-danger"><small>' . $ReturnDatepicker_err . ' </small></p>'; ?>
</div>
</div>
</div>
<div>
<button type="submit" name="confirm" class="btn btn-primary btn-lg " id="confirm">Confirm</button>
</div>
</form>
And my php
<?php
$OnewayDatepicker_err = "";
$RetunDatepicker_err = "";
$OnewayDatepicker = $_POST['OnewayDatepicker'];
$RetunDatepicker = $_POST['RetunDatepicker'];
$hiddeninput = $_POST['hiddeninput'];
if (isset($_POST["confirm"])) {
if (empty($OnewayDatepicker)) {
$OnewayDatepicker_err = " * Choose Departure Date";
} else {
$OnewayDatepicker_err = "";
}
if ((empty($RetunDatepicker)) && ($hiddeninput == "return")) {
$RetunDatepicker_err = " * Choose Return Date";
} else {
$RetunDatepicker_err = "";
}
}
?>
Everything works fine except this part of the code "&& ($hiddeninput = "return")".
it seems php doesn't recognize the value the JS has passed into the hidden input or am i doing something wrong?

jquery sortable not working on dynamically added items

I am trying to get .sortable from jQuery UI to work but it is only working for my first item, when I dynamically add new ones, it stops working.
I found this: http://api.jqueryui.com/sortable/#method-refresh which should refresh everything and recognize new items, but when I use that I get the error:
Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'refresh'
What can I do?
My code:
// HTML template for new fields
const template = `<div class="row sortwrap">
<div class="col-md-8">
<input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
<i class="mdi mdi-sort dragndrop"></i>
<div class="questionlist">
<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-success questionbutton">Extra vraag</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
const vraagTemplate = `<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
$('.sortwrap').sortable();
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
$('.sortwrap').sortable("refresh");
$('#dynamic_field input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
$('#dynamic_field .sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
$('#dynamic_field .questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append category template
$('#addcategory').click(function() {
$('#dynamic_field').append($(template));
updatePlaceholders();
});
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
$ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
If I remove the line that says refresh in my function and only have the one .sortable in my code then I can drag all items even new ones but nothing is dropping. So I can drag but not sort/drop.
I think this is on where you attach your sort. I used a wrapper here to do so.
Note I turned off the refresh due to where I attached it as it seems to not need that given that attachment point.
// HTML template for new fields
const template = '<div class="row sortwrap"> <div class="col-md-8"> <input type="text" name="category[]" placeholder="" class="form-control name_list catinput" /> <i class="mdi mdi-sort dragndrop"></i> <div class="questionlist"> <div class="row"> <div class="col-md-8"> <input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-success questionbutton">Extra vraag</button> </div> </div> </div> </div> <div class="col-md-4"> <button id="addcategory" class="btn btn-danger btn_remove">X</button> </div> </div>';
const vraagTemplate = '<div class="row"> <div class="col-md-8"> <input type="text" name="question[]" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-danger btn_remove">X</button> </div> </div>';
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
// $('#dynamic_field').sortable( "refresh" );
let df = $('#dynamic_field');
df.find('input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
df.find('.sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
df.find('.questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
let $ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(function() {
$('#addcategory').trigger('click');
$('#dynamic_field').sortable();
});
.sortwrap{border: solid green 1px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<button id="addcategory">add</button>
</div>
<div id="dynamic_field"></div>
As mentioned above this will work fine
This looks promising:
http://api.jqueryui.com/sortable/#method-refresh
it seems to imply that you can just add an item to a sortable, then call
$('#mysortable').sortable('refresh')
to recognize it.
var counter = 1;
function appendThing() {
$("<li id='Text" + counter + "' class='ui-state-default'>Text" + counter + "</li>").appendTo($("#mySortable"));
$("#mySortable").sortable({ refresh: mySortable })
counter++;
};
please take a look into this
https://jsfiddle.net/6ztrdg9n/

Laravel 5.2/jQuery - Access DOM element created with Ajax success, in new change event

I've been coding for years, but only in recent months I started looking into JavaScript/jQuery/Ajax. I have searched for days, but none of the answers I see match what I'm trying to do (as far as I can see).
I have a select that gets a list of agendas from the controller. After an agenda is selected, an Ajax call is triggered to get related subjects from the database, and add it as radio inputs to a predefined div. There is already a radio button group for "time assignment per group", where, depending on your selected option, the right set of input fields is displayed.
This works fine for adding the info, but now I want to edit existing records on this same page. So now I want to select an agenda, get the subjects, have the system check if there are already time assignments for the subject I select. If there are, display the correct fields with the data preloaded. If not, treat it like an Add form.
My select works as expected, the Ajax call also creates the needed radio buttons, but how do I access those newly created radio buttons, to start a new Ajax call on that element, to check if there are already assignments?
SELECT
<form accept-charset="UTF-8" class="form-horizontal">
{{ csrf_field() }}
<div class="form-group">
<label for="agenda" class="col-sm-3 control-label">Agenda</label>
<div class="col-sm-6">
<select class="form-control" id="agenda" name="agenda">
<option value="">Selecteer een agenda</option>
#foreach($agendas as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
</div>
</form>
<form method="POST" action="{{ action('TimeController#store') }}" accept-charset="UTF-8" class="form-horizontal">
{{ csrf_field() }}
<div class="form-group"><div id="insertSubjects"></div></div>
<div class="form-group">
<label for="all_type" class="col-sm-3 control-label">Allocatie type</label>
<div class="col-sm-6">
<input type="radio" name="type" id="user" value="1"> User<br>
<input type="radio" name="type" id="fraction" value="2"> Fractie<br>
<input type="radio" name="type" id="oppcoa" value="3"> Oppositie/Coalitie
</div>
</div>
<div id="insertFields"></div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<input class="btn btn-default" type="submit" value="Voeg toe">
</div>
</div>
</form>
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('#agenda').on('change', function() {
var agenda = $('#agenda option:selected').attr('value');
var my_url = window.location.pathname + '/agenda/' + agenda;
$.ajax({
type: "post",
url: my_url,
headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()},
dataType: 'json',
context: this,
success: function (data) {
var fields = '<label for="subject" class="col-sm-3 control-label">Selecteer onderwerp</label>' +
'<div class="col-sm-6">';
jQuery.each(data, function (k, v) {
fields += '<input type="radio" name="subject" value="' + v.id + '" class="subject_radio"> ' + v.subject + '<br>';
});
fields += '</div>';
$('#insertSubjects').html(fields);
$('input:radio[name=subject]:first').attr('checked', true);
}
})
});
$('input[type=radio][name=type]').change(function() {
var fields;
if (this.id == 'user') {
fields = '<div class="form-group"><label for="per_user" class="col-sm-3 control-label">Per lid</label><div class="col-sm-6"><input type="text" name="per_user" id="per_user" /></div></div>';
}
else if (this.id == 'fraction') {
fields = '<div class="form-group"><label for="NDP" class="col-sm-3 control-label">NDP</label><div class="col-sm-6"><input type="text" name="NDP" id="NDP" /></div></div>' +
'<div class="form-group"><label for="VHP" class="col-sm-3 control-label">VHP</label><div class="col-sm-6"><input type="text" name="VHP" id="VHP" /></div></div>' +
'<div class="form-group"><label for="ABOP" class="col-sm-3 control-label">ABOP</label><div class="col-sm-6"><input type="text" name="ABOP" id="ABOP" /></div></div>' +
'<div class="form-group"><label for="PL" class="col-sm-3 control-label">PL</label><div class="col-sm-6"><input type="text" name="PL" id="PL" /></div></div>' +
'<div class="form-group"><label for="BEP" class="col-sm-3 control-label">BEP</label><div class="col-sm-6"><input type="text" name="BEP" id="BEP" /></div></div>' +
'<div class="form-group"><label for="NPS" class="col-sm-3 control-label">NPS</label><div class="col-sm-6"><input type="text" name="NPS" id="NPS" /></div></div>' +
'<div class="form-group"><label for="PALU" class="col-sm-3 control-label">PALU</label><div class="col-sm-6"><input type="text" name="PALU" id="PALU" /></div></div>' +
'<div class="form-group"><label for="DOE" class="col-sm-3 control-label">DOE</label><div class="col-sm-6"><input type="text" name="DOE" id="DOE" /></div></div>' +
'<div class="form-group"><label for="Onbekend" class="col-sm-3 control-label">Onbekend</label><div class="col-sm-6"><input type="text" name="Onbekend" id="Onbekend" /></div></div>';
}
else if (this.id == 'oppcoa') {
fields = '<div class="form-group"><label for="Coalitie" class="col-sm-3 control-label">Coalitie</label><div class="col-sm-6"><input type="text" name="Coalitie" id="Coalitie" /></div></div>' +
'<div class="form-group"><label for="Oppositie" class="col-sm-3 control-label">Oppositie</label><div class="col-sm-6"><input type="text" name="Oppositie" id="Oppositie" /></div></div>' +
'<div class="form-group"><label for="Neutraal" class="col-sm-3 control-label">Neutraal</label><div class="col-sm-6"><input type="text" name="Neutraal" id="Neutraal" /></div></div>';
}
$('#insertFields').html(fields);
});
});
</script>
All the Ajax requests just return JSON encoded data from the database, but if you guys need to see those calls too, let me know. Please guide me in the right direction...
You can create array which will hold the newly created radios buttons.
var newRdoBtnsArr = []; // Array to hold the newly created new radio buttons
$.ajax({
.
.
.
.
success: function (data) {
var newRdoBtn = '<input type="radio" name="subject" value="' + v.id + '" class="subject_radio"> ';
newRdoBtnsArr.push( $( newRdoBtn ) ); // Push the radio button as jQuery object
fields += newRdoBtn + v.subject + '<br>';
.
.
.
.
});
Update after the comment:
I guess you need to execute a AJAX call when there is a change in newly created radio buttons. In that case you can add below lines and try. Like you did for $('input[type=radio][name=type]').change(function() {
$( 'body' ).on( 'change', 'input:radio[name=subject]', function() {
console.log("It works");
} );

jQuery - Event delegation only targeting first newly-created element

I'm trying to create a simple reddit-like system where a user can add a post and then interact with the voting system (which pastes along with the form).
While I have utilized event delegation, it only seems to be affecting my first newly-created element. Thus, on the first newly-created element, the voting system works.
On the latter ones, however, what seems to happen is that the event does get attached, but it updates the first voting system (every post gets a little voting system attached to it).
Any help is appreciated! Thank you.
$("#subbtn").on("click", function(event){
event.preventDefault();
var postTitle = $("#title").val(),
postBody = $("#content").val();
$("#title").val("");
$("#content").val("");
var html = "<div class='wrapper'><div class='panel panel-default'><p class='button' id='plus'>+</p><p id='count'>0</p><p class='button' id='minus'>-</p><h3>'" + postTitle + "</h3><p>" + postBody + "</p></div></div>";
$("body").append(html);
});
var counter = 0;
$(document).on("click", "#plus", function() {
counter++;
$("#count").text(counter);
});
$(document).on("click","#minus", function() {
counter--;
$("#count").text(counter);
});
My HTML is:
<body>
<div class="panel panel-default" id="formStuff">
<div class="form-group">
<label for="title">Title </label> </label>
<input type="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content </label>
<textArea rows="5" type="content" id="content" class="form-control"></textArea>
</div>
<input type="submit" class="btn btn-success" id="subbtn">
</div>
</body>
You are adding multiple voting systems with same IDs plus,count and minus. But Ids should be unique. Instead use classes with same classes and make the selector work on the classes. Please check below snippet for more understanding.
$("#subbtn").on("click", function(event){
event.preventDefault();
var postTitle = $("#title").val(),
postBody = $("#content").val();
$("#title").val("");
$("#content").val("");
var html = "<div class='wrapper'><div class='panel panel-default'><p class='button plus'>+</p><p class='count'>0</p><p class='button minus'>-</p><h3>'" + postTitle + "</h3><p>" + postBody + "</p></div></div>";
$("body").append(html);
});
$(document).on("click", ".plus", function() {
var counter = $(this).siblings(".count").text();
counter++;
$(this).siblings(".count").text(counter);
});
$(document).on("click",".minus", function() {
counter--;
var counter = $(this).siblings(".count").text();
counter--;
$(this).siblings(".count").text(counter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-default" id="formStuff">
<div class="form-group">
<label for="title">Title </label> </label>
<input type="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content </label>
<textArea rows="5" type="content" id="content" class="form-control"></textArea>
</div>
<input type="submit" class="btn btn-success" id="subbtn" />
</div>
This is happening because of the following line:
$(document).on("click", "#plus", function() {...});
// here you are using id selector which are unique.

Categories

Resources