how to implement my button? - javascript

So, I am making a school based project, and it has to be done in javascript and jquery. However these languages are quite new to me, so it's a bit of difficulty for me. My question: how can I append my button so it can submit the form that I have filled out?
a fiddle for u to get an idea of it. I want my button to be placed next to the green one, please do not mind the red minus button. that's something in progress. jsfiddle.net/DanDy/hqy73b0h
underneath is the code that I want to implement:
function submitCSMBtn(target, i) {
var submitBtn = $('<button/>', {
'class': 'btn btn-info fa fa-download',
'type': 'submit',
});
return submitBtn;
}
all the code in case you need to review it as a whole:
$(document).ready(function(){
var id = 0;
var addOpdracht = $('<a/>', {
'class': 'btn btn-success',
'id': 'addOpdracht'
}).on('click', function(){
$('form').append(getExerciseBlock(id));
id++;
}).html('<i class="fa fa-plus"></i>');
$('form').append(addOpdracht);
})
function getAddBtn(target, i){
var addBtn = $('<a/>', {
'class': 'btn btn-primary'
}).on('click', function(){
$(target).append(getWordPartInput(i));
}).html('<i class="fa fa-plus"></i>');
console.log(target);
return addBtn;
}
function getExerciseBlock(i){
var eBlock = $('<div/>',{
'id': i,
'class': 'col-md-12, eBlock'
});
$(eBlock).append(getAudioBtn(i), getWordInput(i), getWordPartInput(i),
getAddBtn(eBlock, i));
return eBlock;
}
function getAudioBtn(id, cValue){
cValue = cValue || '';
var audioBtn = $('<a/>', {
'class': 'btn btn-primary'
}).html('<i class="fa fa-volume-up"></i>');
return audioBtn;
}
function getWordInput(id, cValue){
cValue = cValue || '';
var wInput = $('<input/>', {
'class': 'form-group form-control',
'type': 'text',
'name': 'question_takeAudio_exerciseWord[]',
'placeholder': 'Exercise',
'id': 'exerciseGetWordInput'
})
return wInput;
}
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control',
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'id': 'SyllablesGetWordPartInput'
});
return wpInput;
}
function submitCSMBtn(target, i) {
var submitBtn = $('<button/>', {
'class': 'btn btn-info fa fa-download',
'type': 'submit',
});
return submitBtn;
}
I am trying to add my submit button so it will submit the form (has to go to JSON, maybe that will have a different approach... just giving extra info). from what I know I should use something with the command .on('click', function()) if not mistaken, and it should go in my eBlock if not mistaken either, but whenever I try this it will result in me losing functionality (ea, adding inputs etc. but I keep the layout). I have been looking around however to get a clear explaination of the on('click') function because it's new to me. what I have found was http://api.jquery.com/on/
not sure if this is the same. So if you guys could help me along, that would be great!
EDIT: my HTML code aswell. Apparentely that's needed too, sorry.
NOTE: I just took the code from body to body instead of putting the useless code in it aswell.
<body>
<div class="container">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<h2 id="exerciseTitleCMS" class="col-md-8 col-sm-7 col-xs-6">CMS</h2>
<div class="col-md-offset-2 col-md-2">
<h2>
<select class="languageSelector form-control required" id="languageSelector" ></select>
</h2>
</div>
</div>
</div> <!-- end of panel-heading -->
<div class="panel-body">
<div class="jumbotron" id="mainList">
<form class="container-fluid" action="#" method="POST" required>
</form>
</div>
</div> <!-- end of panel-body -->
</div> <!-- end panel-primary -->
</div> <!--end panel-group -->
</div> <!-- end of container-->
</body>

Try this:
$('<button></button>')
.addClass('btn-class')
.attr('type', 'submit')
.appendTo('form-selector');
But rather than dynamically adding the submit button, you could also put the button in the HTML form, and then programmatically showing it on some event:
With jQuery:
$(function() {
$('#submit_button').hide();
$('#show_submit_button').on('click', function() {
$('#submit_button').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='my_form' class='my_form_class'>
<input type='submit' id='submit_button' />
</form>
<button id='show_submit_button'>Show submit button!</button>
Or with CSS (and jQuery):
$(function() {
$('#toggle_submit_button').on('click', function() {
$('#submit_button').toggleClass('hidden_submit_buttton shown_submit_button');
});
});
.hidden_submit_button {
display: none;
}
.shown_submit_button {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='my_form' class='my_form_class'>
<input type='submit' id='submit_button' class='hidden_submit_button' />
</form>
<button id='toggle_submit_button'>Show/Hide submit button!</button>

You are doing it wrong.
There are few ways to append object.
instead of:
function submitCSMBtn(target, i) {
var submitBtn = $('<button/>', {
'class': 'btn btn-info fa fa-download',
'type': 'submit',
});
return submitBtn;
}
Most easiest way is you can append just plain html string:
var submitBtn = '<button class=\'btn btn-info fa fa-download\' type=\'submit\'><button />';
//then you can append the html string to element you want to append:
$('#your_element_ID').append(submitBtn);

Related

Javascript handle condition before form is submitted

I need to submit a form based on a condition. If true send the form via a modal or simply submit the form directly. What happens is that even when the condition is true the form is sent anyways without waiting that the click on the modal is triggered. After my research I understood that there was a way to prevent the submit with e.preventDefault();. I haven't been able to get the result I want since it just did stop the execution.
(function($) {
$(document).ready(function() {
$( "#save" ).click(function(e) {
if (selectedValIndConstitutionCan === 'waiting'){
$("#form").on('submit', function(e){
e.preventDefault();
});
$('#popupConfirmationEnregistrement').modal("show");
}
$("#confirmYesButtonModal").click(function() {
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
showProgress();
});
showProgress();
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
});
selectDeselectRadioButtons();
});
})(jQuery);
HTML and JSP
<%# include file="/WEB-INF/pages/include/include.jsp" %>
<script src="${contextpath}/js/inputMask/jquery.mask.min.js"></script>
<script type="text/javascript">
</script>
<form:form id="form" modelAttribute="formSaving" action="#">
<fwd:csrfToken />
<div class="row form-group boutons-margin-top">
<div class="col-xs-offset-12 col-xs-12 control-label text-left">
<button class="btn btn-primary" type="button" id="save" data-toggle="modal" data-target="#modalSave">
<spring:message code="xxx.save"/>
</button>
</div>
</div>
</div>
</div>
</c:otherwise>
</c:choose>
</form:form>
<div id="modalSave" class="modal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body">
<spring:message code="msg"/>
</div>
<div class="modal-footer">
<button id="confirmNo" class="btn btn-default" data-dismiss="modal"><spring:message code="no"/></button>
<button id="confirmYesButtonModal" class="btn btn-primary" data-dismiss="modal"><spring:message code="yes"/></button>
</div>
</div>
</div>
</div>
If you click 'save' button, its will submit it anyway in here.
showProgress();
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
I'm not sure why, but if what you want submit it when selectedValIndConstitutionCan is not 'waiting', use else.
(function($) {
$(document).ready(function() {
$( "#save" ).click(function(e) {
if (selectedValIndConstitutionCan === 'waiting'){
$("#form").on('submit', function(e){
e.preventDefault();
});
$('#popupConfirmationEnregistrement').modal("show");
}else{
showProgress();
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
}
$("#confirmYesButtonModal").click(function() {
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
showProgress();
});
});
selectDeselectRadioButtons();
});
})(jQuery);
So finally it is working I had indeed to put the logic in the else clause in case no waiting value is selected AND put the radiobuttons definition variable inside the save on click event
$( "#enregistrer" ).click(function() {
var selectedValIndConstitutionCan = $("[name='infoFiscale.indConstitutionCanada']:checked").val();
if (selectedValIndConstitutionCan === 'waiting'){
$("#popupConfirmationEnregistrement").modal("show");
$('#confirmationEnregistrerOui').on('click', function() {
$("#declarationImpot").attr(
'action',
CHEMIN_CONTEXTE +
'/declarationImpot/enregistrer');
$("#declarationImpot").submit();
affichePopupVeuillezPatienterModaleGenerique();
});
} else {
affichePopupVeuillezPatienterModaleGenerique();
$("#declarationImpot").attr(
'action',
CHEMIN_CONTEXTE +
'/declarationImpot/enregistrer');
$("#declarationImpot").submit();
}
});

jquery add element to first child?

I have a simple section with two buttons these elements are created dynamically, I want to append input to a first button using jquery.
Here is my solution
HTML
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="3" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span></div>
<div buttonid="81" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span></div>
</div>
Js
var getButons = $('.video-btns').attr('buttonid');
var targetmovieid = $(videobtns).attr('targetmovieid');
if(getButons == 81 && targetmovieid =='undefined'){
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'></input>");
inputf.appendTo('.video-btns');
}else{
console.log('something is fucking wrong');
}
Now when I run my app I get the following result
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="81" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span>
<input id="username" style="background: red" class="sync-element" starttime="3" endtime="6">
</div>
<div buttonid="3" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span>
<input id="username" style="background: red" class="sync-element" starttime="3" endtime="6">
</div>
</div>
My code adds to both buttons I just want to add to the button with buttonid=81
what am I doing wrong?
$('.video-btns').each(function() {
var getButons = $(this).attr('buttonid');
var targetmovieid = $(this).attr('targetmovieid');
if (getButons == 81 && targetmovieid == 'undefined') {
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'></input>");
inputf.appendTo(this);
} else {
console.log('something is fucking wrong');
}
});
Not sure if this is what you are looking for, but if you change your JS code to this:
$('.video-btns').each(function(key, value) {
let buttonid = $(this).attr("buttonid");
let targetmovieid = $(this).attr("targetmovieid");
console.log(buttonid + ', ' + targetmovieid)
if(buttonid == 81 && targetmovieid =='undefined'){
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'></input>");
inputf.appendTo($(this));
}
});
It will append the input to the buttons that meet your criteria by looping through them and getting those that match, #Tyddlywink mentions.
You could probably do some filtering or pass in some parameters for the buttonid and the targetmovieid to make it more generalized to suit your needs.
https://jsfiddle.net/tyddlywink/6b2frvz8/
do this instead var getButons = $('.video-btns') then loop through the results $.each(getButons) checking the buttonid of each item.
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="3" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span></div>
<div buttonid="81" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span></div>
</div>
Javascript:
$(document).ready(function() {
var getButons = $('.video-btns');
$.each(getButons, function() {
var targetmovieid = $(this).attr('targetmovieid');
if ($(this).attr("buttonid") == 81 && targetmovieid == 'undefined') {
var inputf = $("<input id='username' style='background: red' class='sync-element' starttime='3' endtime='6'> </input>");
inputf.appendTo($(this));
} else {
console.log('something is Family Show wrong');
}
})
})
You are targeting the appendTo to all elements with class video-btns, not just the one with the two attributes as specified in the if condition. Furthermore, when you get attr() of a jQuery collection, you get the result for the first element in that collection, not of any in that collection.
You can make your life easier by selecting immediately the button you need, including the conditions on the two attributes in the selector, using the square bracket notation:
var $btn = $('.video-btns[buttonid=81][targetmovieid=undefined]');
if (!$btn.length) {
console.log('something is very wrong');
} else {
$btn.append($("<input>", { id: 'username', style: 'background: red', class: 'sync-element', starttime: 3, endtime: 6 }));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="interactive-layers">
<div class="go_back">Go back</div>
<div buttonid="3" class="video-btns show" targetmovieid="4" starttime="2.44" endtime="8.36">
<span class="label">Submit</span></div>
<div buttonid="81" class="video-btns show" targetmovieid="undefined" starttime="2.44" endtime="8.36">
<span class="label">undefined</span></div>
</div>
You are appending the input to .video-btns class, and hence the element is getting added to both the buttons. Try appending using the Id instead of the class.
Edited:
var $btn = $('.video-btns');
$.each($btn, (index, currentBtn) => {
if($(currentBtn).attr('buttonid') == '81' && $(currentBtn).attr('targetmovieid') == "undefined")
{
$(currentBtn).append($("<input>", { id: 'username', style: 'background: red', class: 'sync-element', starttime: 3, endtime: 6 }));
}
})

jQuery sortable in nested element

I have a list with categories and questions (which can both be added dynamically), at the moment I am able to sort the categories using jQuery sortable, but not the questions underneath the categories.
I've tried just adding another .sortable function on the question wrap element but it is not responding at all.
My code at the moment:
// 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 questionwrap">
<div class="row">
<div class="col-md-8">
<button class="btn btn-success questionbutton">Extra vraag</button>
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove removebutton">X</button>
</div>
</div>`;
const vraagTemplate = `
<div class="row" id="question">
<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');
$('#question').sortable();
$('#dynamic_field').sortable({
cancel: '.questionwrap',
placeholder: "ui-state-highlight"
});
});
This is my sortable code:
$(function() {
$('#addcategory').trigger('click');
$('#question').sortable();
$('#dynamic_field').sortable({
cancel: '.questionwrap',
placeholder: "ui-state-highlight"
});
#question is the wrap of my question list and #dynamic_field is the wrap of my category element (the questions are also inside this element).
How can I make my questions also sortable? And also only make then sortable inside their parent div (so I can't drag a question from one category to the other but only within its own category).
One of the first thing I have noticed about your code is that the ID is repeated for each creation of a dynamic element. This will cause a lot of issues when you have 6 #question elements. This can be addressed by adding the ID to the element when it's created and creating a unique ID. For example, if there are 0 #questions then you can count that and add 1.
<div id="question-1"></div>
<script>
var id = $("[id|='question']").length + 1;
</script>
In this, id would be 2. there is one element that contains "question" and the |= selector will look for that before the - in a ID name. Can also use ^= selector.
Making use of handle will help a lot too. This will help allow proper sorting of nested items versus their parents. Also containment is helpful here too unless you want to move them between lists.
Consider the following code. It's a little clunky and I hope you can see what I am referring to.
$(function() {
function makeSortable(obj, options) {
console.log("Make Sortable", obj);
obj.sortable(options);
obj.disableSelection();
}
function updateSort(obj) {
console.log("Update Sortable", obj);
obj.sortable("refresh");
}
function addQuestion(q, c) {
console.log("Add Question", q, c);
var makeSort = $("[id|='question']", c).length === 0;
var question = $("<div>", {
class: "question",
id: "question-" + ($("div[id|='question']", c).length + 1)
});
question.append($("<div>", {
class: "col-md-8"
}).html(q));
question.append($("<div>", {
class: "col-md-4"
}).html("<button class='btn btn-danger btn-remove'>X</button>"));
question.appendTo($(".catcontent", c));
console.log(makeSort, question, c);
if (makeSort) {
makeSortable($(".catcontent", c), {
containment: "parent",
items: "> div.question"
});
} else {
updateSort($("[id|='question']", c).eq(0).parent());
}
}
function makeCategory(name) {
console.log("Make Category", name);
var makeSort = $("[id|='category']").length === 0;
var cat = $("<div>", {
class: "category ui-widget",
id: "category-" + ($("[id|='category']").length + 1)
});
cat.append($("<div>", {
class: "cathead ui-widget-header"
}).html(name + "<i class='btn btn-add-question'>+</i>"));
cat.append($("<div>", {
class: "catcontent ui-widget-content col-md-8"
}));
cat.appendTo($("#cat-wrapper"));
if (makeSort) {
makeSortable($("#cat-wrapper"), {
handle: ".cathead",
items: "> div.category"
});
} else {
updateSort($("#cat-wrapper"));
}
}
$('#addcategory').on('click', function() {
let t = $(template);
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(".categorybutton").click(function(e) {
e.preventDefault();
makeCategory($(".catinput").val());
$(".catinput").val("");
});
$(".catwrap").on("click", ".btn-add-question", function(e) {
e.preventDefault();
var resp = prompt("Question to Add:");
addQuestion(resp, $(this).parent().parent());
});
});
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="row sortwrap">
<div class="col-md-8">
New Category
<input type="text" class="form-control catinput" placeholder="Category Name" />
</div>
<div class="col-md-4">
<button class="btn btn-success categorybutton">Add</button>
</div>
</div>
<div id="cat-wrapper" class="row catwrap">
</div>
Hope that helps.

How to get the value of a particular input field using id in the html templates

I have two div html elements with different id and here I am using spinner. Whenever values in the spinner input changes alert box will be displayed.
HTML code
<div id="accordion2" class="panel-group" style="display: block;">
<div id="accordion2" class="panel-group">
<div id="Tea">
<div class="spinner Tea input-group ">
<input type="text" id = "servings" class="form-control input- sm" value="Tea"/>
<div class="input-group-btn-vertical">
<button class="btn Tea btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Tea btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Tea"> Tea </h4>
</div>
<div id="Coffee">
<div class="spinner Coffee input-group ">
<input type="text" id = "servings" class="form-control input-sm" value="Coffee"/>
<div class="input-group-btn-vertical">
<button class="btn Coffee btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Coffee btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Coffee">Coffee</h4>
</div>
</div>
</div>
JQuery code
$(function(){
$('.spinner:first-of-type input').on('click', function() {
$('.spinner:first-of-type input').val(parseInt($('.spinner:first-of-type input').val(), 10) + 1);
var val = $('.spinner:first-of-type input').val();
changeValues(val);
});
$('.spinner:last-of-type input').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
});
function changeValues(value){
alert($('#energy').attr('class').split(' '));
};
});
But in the alert box whenever I click the spinner up arrow only Tea is displayed.
what I expect is when the spinner is clicked from Tea div tea should be displayed and when from coffee , coffee should be displayed.Please help me out
I'm not sure I totally got what you are trying to do, but it seems to me that you want to increment and decrement number of beverage cups on up/down buttons click. For this you would better modify mark up a little (remove duplicated ids, add classes for convenience). And I may look like this then:
$(function() {
$('.spinner').on('click', '.servings', function(e) {
$(this).val(parseInt($(this).val() || 0, 10) + 1);
var val = $(this).val();
changeValues.call(e.delegateTarget, val);
})
.on('click', '.up', function(e) {
$(e.delegateTarget).find('.servings').val(function() {
return ++this.value;
});
})
.on('click', '.down', function(e) {
var $input = $(e.delegateTarget).find('.servings');
if (+$input.val() > 1) {
$input.val(function() {
return --this.value;
});
}
});
function changeValues(value) {
var type = $(this).find('.energy').data('type');
alert(type);
};
});
Demo: http://plnkr.co/edit/9vXC0RipxkzqhXrHJAKD?p=preview
try this:
$(function () {
$('.spinner').each(function () {
var $el = $(this),
$buttons = $el.find('button'),
$h4 = $el.find('h4'),
input = $el.find('input').get(0);
function showAlert() {
alert($h4.get(0).className);
}
$buttons.eq(0).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) + 1;
showAlert();
});
$buttons.eq(1).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) - 1;
});
});
});
JSFiddle http://jsfiddle.net/yLtn57aw/2/
Hope this helps

Binding to class in knockout.js

I want to bind class of LI/DIV. I'm using knockout.js. I don't know how to make it works. This is my code:
<div id="users-list2" class="span8">
<div class="tabbable">
<!-- Only required for left/right tabs -->
<ul class="nav nav-tabs" data-bind="foreach: conversations">
<li data-bind="click: function () { $root.tabClick(username); }, attr:{ 'class': cls}" style="float:left">
<a class="user-box-name"
data-bind="text: username, attr:{ 'href':'#'+ username }, event: { contextmenu: $root.closeTab }"></a>
</li>
</ul>
<div class="tab-content" data-bind="foreach: conversations">
<div data-bind="attr:{ 'id': username, 'class': 'tab-pane ' + cls}">
<div id="chat-list" class="span12" data-bind="foreach: messages">
<ul>
<li>
<div class="chat-listitem-username" data-bind="text: username">
</div>
<div class="chat-listitem-message" data-bind="html: content">
</div>
<div class="chat-listitem-timestamp" data-bind="text: timestamp.toLocaleTimeString()">
</div>
</li>
</ul>
</div>
</div>
and viewModel:
chatR.conversation = function (username) {
var self = this;
self.messages = ko.observableArray();
self.username = username;
self.test = function (x) { alert(x.username) };
self.cls = "";
}
I want to change cls to "active" when specific tab is clicked and change all others cls to "". It's not working. What am I doing wrong? Classes like "tabbable" and "nav" are defined by bootstrap.js.
EDIT:
This is how I want to chnage cls:
self.tabClick = function (username) {
self.currentConversation = username;
for (i = 0; i < self.conversations().length; i++) {
if (self.conversations()[i].username == username) {
self.conversations()[i].cls = "active";
}
else {
self.conversations()[i].cls = "";
}
}
}
EDIT2:
Changes from comment work, but I have another problem. Li has class "active" but DIC gets:
<div id="aaa_1" class="tab-pane function d(){if(0<arguments.length)
{if(!d.equalityComparer||!d.equalityComparer(c,arguments[0]))d.H(),c=arguments[0],d.G();return this}b.r.Va(d);return c}"
data-bind="attr:{ 'id': username, 'class':'tab-pane '+cls}">
What is wrong here?
Posting the details as an answer.
First Step was to make the cls property an observable and change the code to and change your code accordingly self.conversations()[i].cls("active"); or self.conversations()[i].cls("");
For the second as in edit.
You need output the value of cls and not cls as a whole
So change this
<div data-bind="attr:{ 'id': username, 'class': 'tab-pane ' + cls}">
to
<div data-bind="attr:{ 'id': username, 'class': 'tab-pane ' + cls()}">
Answer to edit 2: instead of
'tab-pane ' + cls
use
'tab-pane ' + cls()
Knockout has special binding for classes, a css binding (http://knockoutjs.com/documentation/css-binding.html).
Example:
<div data-bind='css: {classname: bla() == "something"}'>...</div>

Categories

Resources