Jquery appending form elements and values - php

I am needing a jquery function that checks the database for the max videos allowed for a specific match type of a specified matchID and also the current number of videos already assigned to that particular match.
With this information, I need to construct x amount of inputs (max number of videos for match type) and also populate the inputs where the videos already exist.
For example:
One match could be of type 3 games, which in that case I would need to populate 3 different inputs, also checking to see if the match has videos already existing and filling in those input values with the corresponding video information in order for it to be edited. I completed mostly everything on my own, I have the corresponding inputs displaying fine based on the max amount of videos allowed per that Match Type. The only issue I am having is after generating the inputs, what would be the best way of looping through them based on the videoEditVideoCount ( the total number of videos for the specified match )
To sum it all up:
I have a Edit Video Form
--Dropdown Menu to select which match you would like to edit the videos for
---ON change
---GET max video allowed per match type
---APPEND max video value of inputs to form
function populateEditVideo(matchid){
$.ajax({
url : '/index.php/ajax/populateEditVideo',
type : 'POST',
data : {'matchID' : matchid},
dataType : 'json',
success : function (result) {
$("div#videoEdit").empty();
for(var i = 1; i <= result['videoEditVideoMax']; i++){
$('<label for="videoEditYoutubeURL">Video ' + i + '</label><input name="videoEditYoutubeURL'+i+'" id="videoEditYoutubeURL" type="text" maxlength="16" />').appendTo("div#videoEdit");
}
for(var i = 1; i <= result['videoEditVideoCount']; i++){
$("input#videoEditYoutubeURL"+i).css("background-color", "red");
}
Let's say videoEditVideoCount = 2 and videoEditVideoMax = 3
What I would like to do is append 3 text inputs, and then modify the first 2 input values.
Any help would greatly be appreciated, thanks!

You've got the id of the <input> elements wrong. You forgot to append the number. This would mean the background colour would not change to red.

Related

dynamic calculation of simple math expression

We are taking simple math expression as inputs from user and want to evaluate it. Total number of fields are also dynamic. Each field contains the specific css class as per their index. For example, 1st field has css field "col1", 2nd field has "col2" and so on.
Users gives us input in the form of
"col5 = col4 * col3"
We are converting it to
jQuery(".col5").val(jQuery(".col4").val() * jQuery(".col3").val())
using str_replace function. To do so, we need to do loop for total no of fields. (below is php code example)
for($colLoop = 0; $colLoop < $total_cols; $colLoop++){
$formula = str_replace("col$colLoop","parseFloat(jQuery('.col$colLoop input').val())", $formula);
}
This works but we are looking for some proper solution as it's loops unnecessary for all fields. Is it possible using some other methods? Let us know

Check one column cell to another entire column in PHP

I have a csv file which contain two columns
first column with Part number and second one is Image Name (Multiple Image for each product and Image Name based on Part Number )
I want to check each Part number with entire second column of Image Name each time as this is not sorted properly and store that image name for that perticuler part number in another csv along with that part number.
Current CSV
PartNumber Image Name
WP35001153 35001153R.jpg
WPW10135901 35001153R_Back.jpg
WPW10184873 W10135901R.jpg
WPW10200900 W10135901R_BACK.jpg
WPW10215493 W10137702R.jpg
WPW10249237 W10137702R_Back.jpg
WPW10258402 W10141364R.jpg
WPW10477076 W10477076R.jpg
WP8194064 W10477076R_Back.jpg
W10479760R.jpg
As above csv Part one WP35001153 have two images in on right side 35001153R.jpg and 35001153R_Back.jpg
Also Part number column and Image Column is not perticulary or properly assigned.
So I want to search Part Number with Image name entrie column and if it matches then store in Image1 Column and more than two times it should be store in next column Image2 like below.
PartNumber Image1 Image2
WP35001153 35001153R.jpg 35001153R_Back.jpg
WPW10135901 W10135901R.jpg W10135901R_BACK.jpg
WPW10200900 W10200900.jpg
Please help to figure it out
Thanks
Seem you need to build a new array, using your first column (of csv), cleaned as a key and add to it all you find related too.
Exemple (not exact code)
$mynewarray = [];
foreach ($mycsv as $line) {
$id = $line['PartNumber'];
if ($id[2] == 'W') {
it's a key, clean to obtain : 35001153
mynewarray[$id] = ['pics'=>[ ... ]];
} else {
it's a pic, add the image name
clean the id image name to obtain the key 35001153
mynewarray[$id]['pics'][] = the pics;
}
}
If i understand well your need, this is the idea can solve your problem in one loop with few id analyze.
:) enjoy

PHP - Generating random integers within specified range from a key

I have a set of questions with unique IDs in a MySQL database.
Users also have a unique ID and are to answer these questions and their answers are saved in the database.
Now, I want users to get 5 non-repeating uniquely and randomly picked questions from the pool of available ones (let's say 50) based on users ID. So when a user with id 10 starts answering his questions, but stops and wants to return later to the same page, he will get the same questions as before. A user with id 11 will get a different random set of questions, but it will always be the same for him and different from all other users.
I found that random.org can generate exactly what I need with their sequence generator that generates a random sequence of numbers based on provided ID:
https://www.random.org/sequences/?min=1&max=50&col=1&format=plain&rnd=id.10
But I would like the generation to be done locally instead of relying random.org API.
So, I need to generate 'X' unique random integers, within specified range 'Y' that are generated based on supplied integer 'Z'. I should be able to call a function with 'Z' as parameter and receive back the same 'X' integers every time.
I need to know how to replicate this generation with PHP code or at least a push or hint in a direction of a PHP function, pseudo-code or code snippet that will allow me to do it myself.
Thank you in advance!
Why reinvent the wheel
mt_srand(44);
for ($i=0; $i < 10; $i++) echo mt_rand(). "\n";
echo "\n\n";
mt_srand(44);
for ($i=0; $i < 10; $i++) echo mt_rand(). "\n";
result
362278652
928876241
1914830862
68235862
1599103261
790008503
1366233414
1758526812
771614145
1520717825
362278652
928876241
1914830862
68235862
1599103261
790008503
1366233414
1758526812
771614145
1520717825
Generate your random numbers at the beginning and save it in a session. That way the random numbers for that user is always known and you can know what id of question you should go back to by looking it up in the session.
Cheers
you can get random $w array values. try this code as example and change with your logic.
$w = array('0'=>11,'1'=>22,'2'=>44,'3'=>55,'4'=>66,'5'=>88);
$str = '';
for($i=0;$i<5;$i++) {
$str.= $w[rand(0,5)];
}
As this article suggests, you could use a non-repeating pseudo random number generator. Only problem would be to generate a primnumber that is atleast 2x as big as the upper-bound for IDs and satisfies the condition p = 3 in the ring Z4. Though there should be big-enough primnumbers matching the conditions on the net for free use.
Due to my lack of experience with PHP i can only provide pseudocode though.
int[] generateUniqueRands(int id , int ct)
int[] res
const int prim//the primnumber described above
for int i in [0 , ct[
res[i] = ((id + i) * (id + i)) % prim
return res
Note that this algorithm basically works like a window:
id = x set = [a , b , c , d]
id = x + 1 set = [b , c , d , e]
...
If you wish to avoid this kind of behavior just generate a unique random-number from the id first (can be achieved in the same way the set of random numbers is generated).
When the user with ID 10 opens the page for the first time, use rand() to generate random numbers then store them into a cell in the users table in database. So the user with id 10 has the rand() numbers stored.
For example the users table has id, rand_questions.
Check if the rand_questions is empty then update with the new random numbers generated, else you get the numbers from the database.

elastica scoring based on regular expression using mvel

I am new to elastic search and here is my scenario I am trying to solve.
I have a search input box that supports autosuggestion logic.
The results are fetched from an elastic index which uses ngram filter.
What I want to improve is to introduce a scoring capability so as to order the results from the most important to the less important one (depending on the score).
The score must be based on the following cases:
If there is a match that starts with the given string, set score 100
If there is a match that contains the given string and does not start with it, set score to 10
For this purpose an elastica script was implemented with mvel statements in order to support regular expression match. In other words, it checks to see if the value on the left matches the regular expression on the right (only then a variable is incremented accordingly). But unfortunately it goes wrong when search string is language specific despite the fact that the value on the left is of the specified language too. Another problem to deal with is the second case I mention above (cannot make it to work).
The script when a value ('one example' (belongs to the name field)) starting with the given word ('one') works just fine.
$testParam = mb_strtolower('one', 'utf-8');
$regexStart = '^' . $testParam . '.*$';
$ElasticaScript = new Elastica_Script(" total = 1; if(doc['name'].value ~= '{$regexStart}'){ total += 100; } return total; ");
The script when a value ('one example' (belongs to the name field)) contain the given word ('example') does not work and as a result total score remains 1 and does not increment to 11 as it should be.
$testParam = mb_strtolower('example', 'utf-8');
$regexStart = '^.*' . $testParam . '.*$';
$ElasticaScript = new Elastica_Script(" total = 1; if(doc['name'].value ~= '{$regexStart}'){ total += 10; } return total; ");
And at last, with the same logic, when I try to match a greek word against a value (containing greek letters) of the name field, the increment of the total score is ignored as well.
All the work has been done using the elastica, let alone php.
Could you please help to solve my problem ?
If there is another approach/solution, feel free to share it with me.
Thank you in advance
doc['name'].value loads the analyzed version of the field. Unless your field is set to not analyzed, this will likely be very different than the original content of the field, and not useful for doing regex matches. The Elasticsearch docs on script fields say this only makes sense for non-analyzed or single term fields. For example, if your content is indexed as ngrams, this value will consist of ngrams.
You can access the original text of the field using _source.field_name, and then compute your score based on that. You can still do your search as usual against the ngrams, and use the _source just for scoring.
Here's a sample function_score query that defaults the score to _score, adds 100 if the name field starts with one, else adds 10 if the name field contains one anywhere else. It uses _source.name to access the contents of the name field, so it's doing the regex against the original text of the name field, not the ngrams calculated from the name field.
{
"query": {
"function_score": {
"boost_mode": "replace",
"script_score": {
"script": "total = _score; if (_source.name ~= '^one.*') { total += 100 } else if (_source.name ~= '.*?one.*?') { total += 10 } return total"
}
}
}
}

Maths using javascript and multiple html fields

I have a script that dynamically creates a table with a varying number of columns and rows based on a db query.
This is done twice, on two different db tables.
I have a row at the bottom of each table with an input whose value is the sum of the cells in the column above.
These inputs are named itotal$m (where $m is an incrementing number) for the first table and etotal$m for the second table. So what I end up with is a number of input fields with the names itotal1, itotal2 etc for the first row of totals and etotal1, etotal2 etc for the second row.
I want to perform some simple maths with these totals, subtracting etotal1 from itotal1, etotal2 from itotal2 and so on, then displaying the result in another input.
I would like to use javascript function attached to an onChange event so that the user can change the input box values and see the result.
Unfortunately, I have not managed to figure out how to do this. Any help would be appreciated!
Assuming :
the two tables to have id="iTable" and id="eTable",
all the column total fields to have class="colTotal",
the two tables to be congruous (ie. their columns are in the same order),
the target input elements to have class="diffValue", then :
jQuery:
$(function(){
var $iTableTotals = $("#iTable .colTotal");
var $eTableTotals = $("#eTable .colTotal");
var $diffValues = $(".diffValue");
$(".colTotal").on('change keyup', function() {
$iTableTotals.each(function(i){
var diff = Number($iTableTotals.eq(i).val()) - Number($eTableTotals.eq(i).val());
$diffValues.eq(i).val(diff);
});
});
$iTableTotals.eq(0).change();
});
See fiddle

Categories