Kiroyasha Kiroyasha - 6 months ago 16
HTML Question

I want to create a button along my prepend list item

I recently started JQuery and I need to create a list using the datepicker JQuery function. The problem starts with my prepend because I have to prepend the date I get from the datepicker, the event AND a new button to ERASE whatever's in that line (so the button must be prepended along the list item). I'm having some trouble with this part.

This is the code I have:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Display month &amp; year menus</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<link rel="stylesheet" href="css.css">

<script>
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
});

$(document).on('click', '#bta', '#apagar', function () {

if ($('#datepicker').val() != '' && $('#evento').val() != '' ) {
$('#caixa').prepend('<p>' + $('#datepicker').val() + $('#evento').val() + $('<input type="button" id="apagar" value="apagar" />') + '</p>');
$('input').val('');
}

});

</script>
</head>

<body>
<div id="box">
Lista de Tarefas:
<br><br>
Date: <input type="text" id="datepicker"> &nbsp; &nbsp;

Event: <input type="text" id="evento"> <button id="bta" class="bta">+</button>

<div id="caixa"> </div>
</body>
</div>

</html>


I'm pretty sure this is probably very simple but I've only now started looking around and everything I try to search is either overly complex or doesn't resolve my issue... of course my inability to implement the solutions I find might be very well a problem too.

This is to help visualize my problem

Answer

jQuery.prepend takes argument that are htmlString or Element or Array or jQuery elements. You choose a htmlString, but are adding a jQuery object to this string. This will obviously not work.

What do we actually want? Well, we want to create a <p> tag, then append the datepicker value, the event value and then the button.

var $p = $("<p></p>");
$p.append($('#datepicker').val(), $('#evento').val(), $('<input type="button" id="apagar" value="apagar" />'));
$('#caixa').prepend($p);

Alternatively, skip the step where you turn a string into a jquery object, back into a string.

$('#caixa').prepend('<p>' + $('#datepicker').val() + $('#evento').val() + '<input type="button" id="apagar" value="apagar" /></p>');
Comments